-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathclosestToZeroSum.cpp
More file actions
46 lines (39 loc) · 909 Bytes
/
closestToZeroSum.cpp
File metadata and controls
46 lines (39 loc) · 909 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <stdlib.h>
using namespace std;
int zeroSum(int array[],int size) {
int tempSum;0
int returnSum = array[0]+array[1];
for (int i = 0; i < size; ++i) {
for (int j = i+1; j < size; ++j) {
tempSum = array[i] + array[j];
tempSum = abs(tempSum);
if (tempSum < returnSum) {
returnSum = tempSum;
if (tempSum == 0) {
break;
}
}
}
}
return returnSum;
}
int main(int argc, char const *argv[]) {
int array[20];
int size;
int sum;
cout << "Enter the size of array: ";
cin >> size;
while (size < 2) {
cerr << "ERROR: Size must be greatest than 2.\n";
cout << "Enter the size of array: ";
cin >> size;
}
cout << "Enter the elements of array: ";
for (int i = 0; i < size; ++i) {
cin >> array[i];
}
sum = zeroSum(array,size);
cout << "Minimum sum is " << sum;
return 0;
}