An array is a group of related items that store with a common name.
Syntax
The syntax is as follows for declaring an array −
datatype array_name [size];
Types of arrays
Arrays are broadly classified into three types. They are as follows −
- One – dimensional arrays
- Two – dimensional arrays
- Multi – dimensional arrays
One – dimensional array
The Syntax is as follows −
datatype array name [size]
For example, int a[5]
Initialization
An array can be initialized in two ways, which are as follows −
- Compile time initialization
- Runtime initialization
Example
Following is the C program on compile time initialization −
#include<stdio.h> int main ( ){ int a[5] = {10,20,30,40,50}; int i; printf ("elements of the array are"); for ( i=0; i<5; i++) printf ("%d", a[i]); }
Output
Upon execution, you will receive the following output −
Elements of the array are 10 20 30 40 50
Example
Following is the C program on runtime initialization −
#include<stdio.h> main ( ){ int a[5],i; printf ("enter 5 elements"); for ( i=0; i<5; i++) scanf("%d", &a[i]); printf("elements of the array are"); for (i=0; i<5; i++) printf("%d", a[i]); }
Output
The output is as follows −
enter 5 elements 10 20 30 40 50 elements of the array are : 10 20 30 40 50
Note
The output of compile time initialised program will not change during different runs of the program.
The output of run time initialised program will change for different runs because, user is given a chance of accepting different values during execution.
Example
Following is another C program for one dimensional array −
#include <stdio.h> int main(void){ int a[4]; int b[4] = {1}; int c[4] = {1,2,3,4}; int i; //for loop counter //printing all elements of all arrays printf("\nArray a:\n"); for( i=0; i<4; i++ ) printf("arr[%d]: %d\n",i,a[i]); printf("\nArray b:\n"); for( i=0; i<4; i++) printf("arr[%d]: %d\n",i,b[i]); printf("\nArray c:\n"); for( i=0; i<4; i++ ) printf("arr[%d]: %d\n",i, c[i]); return 0; }
Output
The output is stated below −
Array a: arr[0]: 8 arr[1]: 0 arr[2]: 54 arr[3]: 0 Array b: arr[0]: 1 arr[1]: 0 arr[2]: 0 arr[3]: 0 Array c: arr[0]: 1 arr[1]: 2 arr[2]: 3 arr[3]: 4