Just expanding a little on I love python's comment
You're very close with the code you have already. Short answer: In the loop, remove the space after '%d' and add an addressof operator before arr[i].
But your code probably won't compile at the moment because you actually can't declare an array unless it's size is known at compile time (int arr[n]
). You can, however, dynamically allocate it in memory using malloc()
and free()
(from stdlib.h) as follows:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
printf("Enter the number of elements of the first array: ");
scanf("%d", &n);
// Dynamically allocate the array (allows for variable size)
int* arr = (int*)malloc(n * sizeof(int));
for (int i = 0; i<n; i++) {
// Remove the space after '%d'
// Add addressof operator before arr[i]
scanf("%d", &arr[i]);
}
// Don't forget to free the allocated memory!
free(arr);
return 0;
}
The reason this works is because scanf
returns as soon as it finds the requested input (an int, in this case). When it returns though, everything that it hasn't read gets left in the input buffer. When scanf
executes again, it still has the rest of the user's input to read and it returns after reading the next int, and this keeps repeating until the loop condition is satisfied.