AlphaCodingSkills

C - Arrays


Advertisements

Previous Page Next Page

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. Index number for an Array in C starts with 0.

C Arrays Indexing

Below mentioned example illustrates on indexing for an Array in C.

#include <stdio.h>

int main (){
    int MyArray[5] = {10, 20, 30, 40, 50};
    printf("%i", MyArray[3]); 
    return 0;
}

Output

40

Change 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 (){
    int MyArray[5] = {10, 20, 30, 40, 50};
    MyArray[1] = 100;
    printf("%i", MyArray[1]);
    return 0;
}

Output

100

Loop over an Array

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

For Loop over an Array


#include <stdio.h>
 
int main (){
    int MyArray[5] = {10, 20, 30, 40, 50};
    for(int i = 0; i < 5; i++)
    {
      printf("%i\n", MyArray[i]);     	
    }
    return 0;
}

Output

10
20
30
40
50

While Loop over an Array


#include <stdio.h>
 
int main (){
    int MyArray[5] = {100, 200, 300, 400, 500};
    int i = 0;
    while(i < 5)
    {
      printf("%i\n", MyArray[i]); 
      i++;    	
    }
    return 0;
}

Output

100
200
300
400
500

Multi-dimensional Array

Multi-dimensional array can be viewed as arrays of arrays. C allows you to define array of any dimension.

Syntax


int MyArray [n][m];    //2-dimension array.
int MyArray [p][q][r]; //3-dimension array.
int MyArray [2][3] = {10,20,30}; //2-dimensional array with size (2,3).

#include <stdio.h>
 
int main (){
    int numbers[2][3] = {10, 20, 30, 40, 50, 60};
    for(int i = 0; i < 2; i++)
    {
      for(int j = 0; j < 3; j++)
      {
        cout<<numbers[i][j]<<" ";
      }
      cout<<"\n";
    }
    return 0;
}

Output

10 20 30 
40 50 60 

Previous Page Next Page