Friday, July 29, 2016

C Basics - Arrays in C

An array is a collection of data elements of the same type. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Declaring Arrays:
To declare an array in C, the type of the elements and the number of elements required by an array is mentioned as,

type arrayName [ arraySize ];

This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type.

int sum[5];

Here sum is a variable array which is sufficient to hold up to 5 integer numbers. All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be total size of the array minus 1.

Initializing Array:
An array can be initialized as follows

int sum[5] = {0,1,2,3,4};

If you omit the size of the array, an array just big enough to hold the initialization is created.

int sum[] = {0,1,2,3,4};

To assign a single element of the array,

sum[3] = 3;

Accessing Array Elements:
An element is accessed by indexing the array name.

int total = sum[3];

The above statement will take the 4th element from the array and assign the value to total variable.

#include <stdio.h>

int main () {

   int i[ 3 ] = {0,1,2};
   int temp;
   
   temp = i[0];
   printf("value in i[0] = %d\n", temp );
   temp = i[1];
   printf("value in i[1] = %d\n", temp );
   temp = i[2];
   printf("value in i[2] = %d\n", temp );

 
   return 0;
}
Output of above program,

value in i[0] = 0
value in i[1] = 1
value in i[2] = 2



Related topics:
Two Dimensional Array in C   |   Passing Array as Function Argument in C   |   Strings in C   |   Pointers in C   |   Returning Array from a Function in C

List of topics: C Programming

No comments:

Post a Comment