Array Operations

Initializing an Array

When you declare an array, memory is allocated to store the elements of the array, but these memory locations are not initialized and may contain any random value in it. To assign values to an array element follow the syntax:

arrayname[index1][index2]....[indexN] = value;


myarray[2] = 300;
multiarray[1][3] = 500;

You could also initialize the elements of an array when it is declared. This is done by assigning the initial values separated by comma and enclosed in curly brackets {}. This method can also be used to partially initialize the array in which case the remaining elements are set to 0


// Initialize all elements of the array with the given values
int myarray[5] = {100,200,300,400,500}; 

//Initialize all elements of the array with value 0 
int myarray[5]={0}; 

//Set the first element to 100, second element to 200 and the rest to 0
int myarray[5]={100,200}; 

Accessing the Array

Operations on the array elements like assigning values, arithmetic, logical and matrix operations can be best performed by using loops; typically using the for loop

To increment the value of each element of a two dimensional matrix a[5][4], you can use a nested for loop as below

for (i=0; i<5; i++)
	for(j=0; j<4; j++)
	a[i][j] = a[i][j] + 1;

Post a comment


Your Comment

Email (We dont publish it)


Nothing the first to share wisdom.