Home > Backend Development > C++ > body text

Array operations and sums using C/C++

PHPz
Release: 2023-09-02 22:29:06
forward
1309 people have browsed it

Array operations and sums using C/C++

Here we will see a problem, assuming an array is given. There are n elements. Another value S is also given. We must find an element K in the array such that if all elements greater than K are equal to K, then the sum of all elements of the final array equals S. If not possible, then -1 is returned.

Assume the elements are {12, 6, 3, 7, 8} and the sum value is 15, then the output is 3. The final array is {3, 3, 3, 3, 3}, and the sum of the array elements is S = 15

Algorithm

getVal(arr, n, S)

Begin
   sort arr as increasing order
   sum := 0
   for i in range 0 to n-1, do
      if sum + (arr[i] * (n - i)) is same as S, then
         return arr[i]
      end if
      sum := sum + arr[i]
   done
   return -1
End
Copy after login

Example

#include <iostream>
#include <algorithm>
using namespace std;
int getVal(int arr[], int n, int S) {
   sort(arr, arr + n);
   int sum = 0;
   for (int i = 0; i < n; i++) {
      if (sum + (arr[i] * (n - i)) == S) //if current value is satisfying, then return arr[i]
         return arr[i];
      sum += arr[i];
   }
   return -1;
}
int main() {
   int S = 15;
   int arr[] = { 12, 3, 6, 7, 8 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << getVal(arr, n, S);
}
Copy after login

Output

3
Copy after login

The above is the detailed content of Array operations and sums using C/C++. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!