mchlim
mchlim

Reputation: 3

How to read multiple input in looping

printf("number to input: \n");
scanf("%d",&y);

for(x=0;x<y;x++){
    scanf("%d",&num);
}

printf("Numbers entered: %d \n",num);

let assume that we entered value 4 . scanf will looping 4 times and entered a single value 1,2,3,4 for each loop

The final output should display 1 2 3 4

any ideas?

Upvotes: 0

Views: 769

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

You should use an array to store the values. You will have to allocate dinamically because the number of data varies and it can be determined by user input before reading the data.

Here is a sampie implementation:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int x,y=-1;
    int *num;
    printf("number to input: \n");
    scanf("%d",&y);
    if(y<0)return 1;
    num = malloc(sizeof(int)*y);
    if(num==NULL)return 1;

    for(x=0;x<y;x++){
        scanf("%d",&num[x]);
    }

    printf("Numbers entered: ");
    for(x=0;x<y;x++){
        printf("%d ",num[x]);
    }
    printf("\n");
    free(num);
    return 0;
}

Upvotes: 2

Related Questions