I was writing a code, to find the 2 elements in the array, whose sum is equal to the user input number. I have first sorted the the array, than used variable low and high to mark lower and higher intergers in the array.
In the output the positions are not correct, but if i remove the for loop(i have maked it in the code) the program gives correct output in the sorted array.
Please look into the code and help me to find the error. Here is the code:
// problem in line 47 - 53
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, sum;
cout << "Enter the number of elements in the array: ";
cin >> n;
int arr[n], arr2[n]; //arr2 is used as after arr is sorted, position will be changed
cout << "Enter the elements in the array-\n";
for (int i = 0; i < n; i++)
{
cout << "Element " << i << ": ";
cin >> arr[i];
arr2[i] = arr[i];
}
cout << "Enter the sum you want by two elements: ";
cin >> sum;
// sorting the array --->very important for this method
for (int i = 1; i < n; i++)
{
int current = arr[i];
int j = i - 1;
while (arr[j] > current && j >= 0)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = current;
}
// now finding pairSum
int low = 0;
int high = n - 1;
while (low < high)
{
if (arr[low] + arr[high] == sum)
{
// loop is used for, when we found the elements, to restore their index
for (int i = 0; i < n; i++)
{
if (arr2[i] == arr[low])
low = i; //index retained
if (arr2[i] == arr[high])
high = i; //index retained
}
cout << "Elements are " << low << " and " << high << endl;
return 0;
}
else if (arr[low] + arr[high] < sum)
low++;
else
high--;
}
cout << "Sorry... no such elements found." << endl;
return 0;
}