#include
#include
using namespace std;
int main()
{
int n, key;
cin >> n;
int arr[1000];
for (int k = 0; k < n; k++)
{
cin >> arr[k];
}
cin >> key;
std::sort(arr, arr + n);
int i = 0, j = n - 1;
while (i < j)
{
int current_sum = arr[i] + arr[j];
if (current_sum > key)
{
j--;
}
else if (current_sum < key)
{
i++;
}
else if (current_sum == key)
{
cout << arr[i] << " and " << arr[j] << endl;
i++;
j--;
}
}
return 0;
}
Here when I declare and initialize the variables i and j (line 20) just before while then this code works as in the while loop runs. But when I declare i and j at top (just below int main)
the while loop doesn’t runs. Can you please explain me why?