Home > Blockchain >  Read a list of n numbers and make an array in C
Read a list of n numbers and make an array in C

Time:01-03

So I want to take an input such as this:

the first input tells us the size of the array and the second line contains the numbers of array like this:

input:

3
1 2 3

and I want to make an array from the second input line with a size of from the first input line.

I currently have:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
        int n;
        scanf("%d", n);
        int x[n];
        int y[n];

}

but after which I get stumped

CodePudding user response:

If you have a VLA(Variable Length Array) supporting compiler(eg. GCC):

int n;
scanf("%d", &n);
int arr[n];
scanf("%d %d %d", &arr[0], &arr[1], &arr[2]);

and if not,

int n;
scanf("%d", &n);
int *arr = malloc(n * sizeof(int));
scanf("%d %d %d", &arr[0], &arr[1], &arr[2]);

This code uses the functionality of scanf to be able to take multiple delimited input.

If you have to take n inputs and not only set the size of arr to n, do this:

int n;
scanf("%d", &n);
int arr[n];

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

It should be apparent that VLA functionality lets you to make an array on the stack with a runtime value. Otherwise, you'll need to allocate it on the heap with malloc().

CodePudding user response:

What if there are more than 3 numbers to scan. Do I need to add more "%d" and arr[] or is there some way for it to work with any number of numbers in the second line.

To address this point you can go with iterating over loop

for(int i=0;i<n;i  )
{
scanf("%d",&array[i]);
}
  • Related