Home > Mobile >  Is there a way to add multiple values into an array in one command prompt?
Is there a way to add multiple values into an array in one command prompt?

Time:10-12

I am trying to scanf 5 numbers into an array in one command line prompt. I know how to store a value one by one into an array, but in this case I am trying to store 5 values in a line. I know how to hard code it when the limit is clear, but I want to code it based on a user inputted limit.

for example (hard code):

int arr[5]; 

scanf("%d %d %d %d %d", &arr[0], &arr[1], &arr[2], &arr[3], &arr[4]);

for (i = 0; i < 5; i  ) {
printf(" %d", arr[i]);
}

would give me the values of arr[0] arr[1] arr[2] arr[3] arr[4].

BUT what if the size of aaa is defined by users, or defined by a macro that allows changes? How do you not hard code it?

#define MAX 10

int arr[MAX];

or

printf("what is the limit? : ");
scanf("%d", &limit);

int arr[limit];

I tried using a for loop but it doesn't work.

for(i=0;i<MAX; i  ){
scanf("%d %d %d %d %d\n", &aaa[i]);      //I want user to input 5 numbers in one line, but this format doesnt work.
}

To conclude/clarify my question.

I want user to input 5 numbers in one line. for example : 1 2 3 4 5 with a space in between. and I want it stored at arr[0] arr[1] arr[2] arr[3] arr[4]. Is there a way to not hard code this?

Help would be greatly appreciated! Thanks!

CodePudding user response:

You need to read inputs in the loop as below.

for(i=0;i<MAX; i  ) {
  scanf("%d", &aaa[i]);
}

CodePudding user response:

You want this:

#include <stdio.h>

int main()
{
  int arr[5];

  printf("Enter 5 numbers separated by space then press Enter\n");
  for (int i = 0; i < 5; i  ) {
    scanf("%d", &arr[i]);
  }

  for (int i = 0; i < 5; i  ) {
    printf(" %d", arr[i]);
  }
}

Execution:

Enter 5 numbers separated by space then press Enter
1 2 3 4 5
 1 2 3 4 5
  • Related