C – Array

Prev     Next

C Array is a collection of variables belongings to the same data type. You can store group of data of same data type in an array.

  • Array might be belonging to any of the data types
  • Array size must be a constant value.
  • Always, Contiguous (adjacent) memory locations are used to store array elements in memory.
  • It is a best practice to initialize an array to zero or null while declaring, if we don’t assign any values to array.

Example for C Arrays:

  • int a[10];       // integer array
  • char b[10];    // character array   i.e. string

Types of C arrays:

There are 2 types of C arrays. They are,

  1. One dimensional array
  2. Multi dimensional array
    • Two dimensional array
    • Three dimensional array
    • four dimensional array etc…

1. One dimensional array in C:

Syntax : data-type arr_name[array_size];

Array declaration, initialization and accessing 
Example

Array declaration syntax:
data_type arr_name [arr_size];

Array initialization syntax:
data_type arr_name [arr_size]=(value1, value2, value3,….);

Array accessing syntax:
arr_name[index];

Integer array example:

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

age[0]; /*0 is accessed*/
age[1]; /*1 is accessed*/
age[2]; /*2 is accessed*/

Character array example:

char str[10];
char str[10]={‘H’,‘a’,‘i’};
(or)
char str[0] = ‘H’;
char str[1] = ‘a’;
char str[2] = ‘i;

str[0]; /*H is accessed*/
str[1]; /*a is accessed*/
str[2]; /*i is accessed*/

Example program for one dimensional array in C:

Output:

value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50

2. Two dimensional array in C:

  • Two dimensional array is nothing but array of array.
  • syntax : data_type array_name[num_of_rows][num_of_column];
Array declaration, initialization and accessing 
Example
Array declaration syntax:
data_type arr_name [num_of_rows][num_of_column];

Array initialization syntax:
data_type arr_name[2][2] = {{0,0},{0,1},{1,0},{1,1}};

Array accessing syntax:
arr_name[index];

Integer array example:

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

arr [0] [0] = 1;
arr [0] ]1] = 2;
arr [1][0]  = 3;
arr [1] [1] = 4;

Example program for two dimensional array in C:

Output:

value of arr[0] [0] is 10
value of arr[0] [1] is 20
value of arr[1] [0] is 30
value of arr[1] [1] is 40

Prev     Next




Share this C, SQL, Java programming, JSP & XML tutorial website
Facebook Twitter Linkedin