
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
Array Manipulation and Sum using C/C++
Here we will see one problem, suppose one array is given. There are n elements. Another value S is also given. We have to find an element K in the array, such that, if all elements which are greater than K, are made equal to K, then the sum of all elements of the final array becomes equal to S. If that is not possible, then return -1.
Suppose the elements are {12, 6, 3, 7, 8}, and sum value is 15, the output is 3. The final array is {3, 3, 3, 3, 3}, Sum of 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
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); }
Output
3
- Related Articles
- Array Type Manipulation in C++
- C++ Floating Point Manipulation
- Sum of array using pointer arithmetic in C++
- Sum of array using pointer arithmetic in C
- Bits manipulation (Important tactics) in C++
- Find an element in array such that sum of left array is equal to sum of right array using c++
- Matrix row sum and column sum using C program
- C++ Sum Array Puzzle
- Array sum in C++ STL
- How to calculate sum of array elements using pointers in C language?
- Sorting and find sum of differences for an array using JavaScript
- File system manipulation
- C program to dynamically make array and print elements sum
- A Sum Array Puzzle in C++?
- Split Array Largest Sum in C++

Advertisements