Initialization of variable sized arrays in C

CProgrammingServer Side Programming

Variable sized arrays are data structures whose length is determined at runtime rather than compile time. These arrays are useful in simplifying numerical algorithm programming. The C99 is a C programming standard that allows variable sized arrays.

A program that demonstrates variable sized arrays in C is given as follows −

Example

 Live Demo

#include

int main(){
   int n;

   printf("Enter the size of the array: \n");
   scanf("%d", &n);

   int arr[n];

   for(int i=0; i<n; i++)
   arr[i] = i+1;

   printf("The array elements are: ");

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

   return 0;
}

Output

The output of the above program is as follows −

Enter the size of the array: 10
The array elements are: 1 2 3 4 5 6 7 8 9 10

Now let us understand the above program.

The array arr[ ] is a variable sized array in the above program as its length is determined at run time by the value provided by the user. The code snippet that shows this is as follows:

int n;

printf("Enter the size of the array: \n");
scanf("%d", &n);

int arr[n];

The array elements are initialized using a for loop and then these elements are displayed. The code snippet that shows this is as follows −

for(int i=0; i<n; i++)
arr[i] = i+1;

printf("The array elements are: ");

for(int i=0; i<n; i++)
printf("%d ", arr[i]);
raja
Published on 06-Nov-2018 14:40:46
Advertisements