Program to find the Hidden Number in C++

C++Server Side ProgrammingProgramming

In this problem, we are an array arr[] consisting of n integer values. Our task is to create a Program to find the Hidden Number in C++.

Code description − For an array, the hidden number, is the number which when subtracted from each element of the array gives the sum 0.

Let’s take an example to understand the problem,

Input

arr[] = {4, 1, 6, 7, 2}

Output

4

Subtracting 4 from all elements of the array. And adding of values

= (1 - 4) + (6 - 4) + (7 - 4) + (4 - 2)
= -3 + 2 + 3 - 2 = 0

Solution Approach

To solve the problem, we need to calculate the sum of all elements of the array. And then divide the sum by the total number of elements of the array. If the value of sum / (no of elements) is an integer, it is the hidden number.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
int calcHiddenNumber(int arr[], int n){
   long int sum = 0;
   for(int i = 0; i < n; i++){
      sum = sum + arr[i];
   }
   int hidNum = (sum / n);
   if((hidNum * n) == sum )
      return hidNum;
   else
      return -1;
}
int main() {
   int n = 4;
   int arr[] = { 4, 11, 12, 21 };
   cout<<"The hidden number for the array is "<<calcHiddenNumber(arr, n);
   return 0;
}

Output

The hidden number for the array is 12
raja
Published on 08-Jun-2020 10:33:19
Advertisements