Home » Programming Languages » C Programs » Array Initialisation in C

Array Initialisation in C

Array Initialization in C can be done using multiple methods. We will see examples of the simple techniques to initialize arrays below:

Technique 1:

This is a very simple method to initialize arrays. We will declare and provide elements for the array in the program itself as shown below:

$ vim array.c
#include <stdio.h>

int main(void) {
	int x[2], i;
	x[0] = 4;
	x[1] = 10;
	printf ("x[0] = %d, x[1] = %d \n", x[0], x[1]);
return 0;
}

Technique 2:

The below technique can also be used to initialize arrays. In this method, we provide the elements for the array in a single step during the declaration.

$vim array2.c
#include <stdio.h>

int main(void) {
        int x[] = {4, 10};
        printf ("x[0] = %d, x[1] = %d \n", x[0], x[1]);
return 0;
}

Technique 3:

The below technique is similar to Technique 2 with a slight change. We declare the size of the array during the initialization.

$ vim array3.c
#include <stdio.h>

int main(void) {
        int x[2] = {4, 10};
        printf ("x[0] = %d, x[1] = %d \n", x[0], x[1]);
return 0;
}

Technique 4:

To accept input from users for the array, we use the following method:

$ vim array4.c
#include <stdio.h>

int main(void) {
        int x[2], i;
        printf("Enter values to take from scanf : \n");
        for (i=0; i < 2; i++) {
                scanf("%d", &x[i]);
        }
        printf ("x[0] = %d, x[1] = %d \n", x[0], x[1]);

        return 0;
}

Compiling and executing the programs:

$gcc -o array array.c
$ ./array
x[0] = 4, x[1] = 10
$ gcc -o array2 array2.c
$ ./array2
x[0] = 4, x[1] = 10
$ gcc -o array3 array3.c
$ ./array3
x[0] = 4, x[1] = 10
$ gcc -o array4 array4.c
$ ./array4
Enter values to take from scanf : 
4
10
x[0] = 4, x[1] = 10
8×8 LED Dot Matrix Interfacing usi...
8×8 LED Dot Matrix Interfacing using Arduino Board

Leave a Comment