C PROGRAMMING
MULTIPLE CHOICE QUESTION
OLD QUESTION BANK
SAMPLE QUESTION 2080 AND SOLUTION

Introduction to an Array In C


A variable is capable of holding only one value at a time. Consider a situation in which we need to store a collection of values. For example: store marks obtained by 100 students in a class, we can have two choices for that:

  • Create 100 variables, one variable for each 100 students.
  • Only one variable to hold or store 100 values.

Obviously the second choice is better than the first one. In C programming, we can have a single variable that is capable of holding or storing multiple values of similar data type, called an array.

Definition

Array can be defined as collection of elements of similar data types. For example: an integer array can only store  integer values or a floating point array can only store floating point values. In C programming an array of characters is called a string.

Array Declaration

The general form of array is as follows:

data_type variable_name[Dimension];

Here, data type can be any valid C data type like integer, float,char, double etc, followed by a variable name for the array. The dimension enclosed within [ and ] denotes the size of the array. Based on above syntax, define an array to store age of 100 individuals in a group:

int age[100];

Accessing Array Elements

In C programming, individual array elements can be accessed by using array’s index or subscript. The index of the array starts from 0 to size of array -1. For an array of size 10, its index value will be from 0 to 9. Let us understand following memory map of an array of size 5, to understand indexing and subscript of the array:

Now, the individual elements of the array can be accessed by using its index value. For example: elements at 3rd position can be accessed using age[2]. 

In C programming, for an array, the compiler always reserves contiguous memory location, so for the above array a total of 20 bytes of contiguous memory is allocated to store the age of 5 individuals.

More on array: Declaration and Initialization

Array can be declared and initialized using following ways:

//floating point array of size 10
float z[10];

//It is optional to define array size, when declaration and initialization is in same line
int x[] = {10,20,30};

// here array dimension is optional
char c[3] = {'a','b','c'};

Let us see the memory map of array of size 4:

Another way to initialize array is as follows:

char z[4];
z[0] = 'a';
z[1] = 'b';
z[2] = 'c';
z[3] = 'd';