C Tutorial C References

C - Arrays



Arrays are used to store multiple values in a single variable. In C, all elements of an array must be of same datatype.

Create an Array

It starts with defining the datatype of the array, name of the array followed by size of the array enclosed in square brackets, [ ].

Initialize an Array

An array can be initialized by separating it's elements by comma , and enclosing with curly brackets { }.

Please note the following points while working with Arrays:

  • Array can be initialized later using index, if it not initialized at the time of declaration.
  • If a variable is used for the size of array, then the variable must not be unassigned before declaring the array.

Syntax

//declaring an array of size 3.
int MyArray [3];  

//array of size 'n'. 
//'n' must have assigned value before declaration.
float MyArray [n]; 

//declaring and initializing an array of size 3.  
int MyArray [3] = {10,20,30}; 

Access element of an Array

An element of an array can be accessed with it's index number. In C, the index number of an array starts with 0 as shown in the figure below:

C Arrays Indexing

The example below describes how to access elements of an array using its index number.

#include <stdio.h>

int main (){
  //creating an array with 5 elements
  int MyArray[5] = {10, 20, 30, 40, 50};

  //accessing the element with index number 3
  printf("%i", MyArray[3]); 
  return 0;
}

The output of the above code will be:

40

Modify elements of an Array

Any element of an Array can be changed using its index number and assigning a new value.

#include <stdio.h>
 
int main (){
  //creating an array with 5 elements
  int MyArray[5] = {10, 20, 30, 40, 50};

  //modifying elements
  MyArray[1] = 100;

  //displaying the result
  printf("%i", MyArray[1]);
  return 0;
}

The output of the above code will be:

100

Loop over an Array

With for loop or while loop, we can access each elements of an array.

For Loop over an Array

In the example below, for loop is used to access all elements of the given array.

#include <stdio.h>
 
int main (){
  int MyArray[5] = {10, 20, 30, 40, 50};

  //using for loop to access all 
  //elements of the array
  for(int i = 0; i < 5; i++) {
    printf("%i\n", MyArray[i]);     	
  }
  return 0;
}

The output of the above code will be:

10
20
30
40
50

While Loop over an Array

Similarly, while loop is also be used to access elements of the array.

#include <stdio.h>
 
int main (){
  int MyArray[5] = {100, 200, 300, 400, 500};
  int i = 0;

  //using while loop to access all 
  //elements of the array
  while(i < 5) {
    printf("%i\n", MyArray[i]); 
    i++;    	
  }
  return 0;
}

The output of the above code will be:

100
200
300
400
500