How to input 'n' space separated integers?

LANGUAGE : C

‘n’ is an integer that will be entered by the user. In the next line, I want to enter ‘n’ integers. ‘n’ can be an integer less than 100. Is this possible using the scanf function? If not, suggest some other method. How can I store these ‘n’ integers in an array.

Use a simple for loop.

int i, n, arr[100];

scanf("%d", &n);
for (i = 0; i < n; ++i)
    scanf("%d", &arr[i]);

The above code snippet would do.

3 Likes

#include<stdio.h>
#define MAX 100
int main()
{
int n,array[MAX];
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&array[i]); // scan and store in the array[]
return 0;
}

3 Likes

@tijoforyou I had already used this in solving some questions but when I saw this input format in yesterday’s DIVQUERY problem, I could not think of any way of doing this. -_- Thanks a lot.

1 Like

@charizard Thanks a lot.

scanf (and cin, for the record) by defaults splits the input based on whitespaces. So, spaces, tabs, newlines etc are ignored.

1 Like