Home > Blockchain >  Reading N elements in one line in C
Reading N elements in one line in C

Time:03-14

I have recently started to pick up learning C by solving competitive programming challenges and thelike, but I have run into an issue; is there any way to read an unknown/changing amount of elements in one line?

For example, if I wanted to read only one element in a line, I would do:

cin >> x;

For 2 elements:

cin >> x >> y;

etc., but is there any way to read a changing amount of these? Say I am given a number N that represents the amount of elements in one line I would have to read, is there any neat way to go about this? Thanks in advance

CodePudding user response:

You can just create a while loop, and use an array to store your inputs like this :

`int i = 0, tab[20];

while(i < 20)
{
cin >> tab[i];
i  ;
}`

here, you can store 20 values in the array called tab.

CodePudding user response:

For an instance let's suppose you have an array in which you have n elements and you want to print them. So here you can use for & while loop for simplicity and fastest way.

example:

int n; // n elements
int data[n] = { 2, 3, 4, 5, ... ,n}; // array

for (int i = 0; i < n; i  ) {
    cout << data[i] << ", "; 
}

while loop example is given in the above answer.

  • Related