I'm going through the challenges for C++ on HackerRank and I've gotten stuck at the arrays introduction. It's giving me a sample input of
4
1 4 3 2
Where n=4 is the size of the array and the following line gives the array with n random integers. I ran into an issue with n=4 changing after my first for loop when answering the question, so I've been messing with it to try to understand it.
At the moment, I'm simply trying to scan the sample input numbers but n keeps changing once I've scanned the last element of the array:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n, arr[n];
scanf("%d", &n);
printf("%d \n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
printf("%d ", arr[i]);
printf("n=");
printf("%d ", n);
}
printf("\n%d", n);
return 0;
}
which gives me the following output:
4
1 n=4 4 n=4 3 n=4 2 n=2
2
Can anyone explain why n changes to a 2 after the final loop and stays as n=2 for all subsequent uses? How is it affected when I haven't assigned it to anything? This is the only sample input they give me as practice but they try a lot more with 1<=n<=1000 after I submit it and I want to understand it without cheating.