While loop and variable initialization

#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?

so basically u declare it anywhere in main but should be after taking input of n only

ok sir thanks for helping out.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.