C Array

Introduction

Array is a group of variable which shares the common name. A particular number in array is accessed by index number or subscript in square brackets after the array name.

An individual value of an array is known as element or array element. For example, int marks [10], is an array of integer data type for ten elements, and the complete set of values for ten marks is known as an array.

  • An array is a collection of elements of the same type that are referenced by a common name.
  • Compared to the basic data type (int, float, char), it is an aggregate or derived data type.
  • All the elements of an array occupy a set of contiguous memory locations.
  • Why need to use array type?
  • Consider the following issue:
    • Assume, we have a list of 1000 students’ marks of an integer type.
    • If using the basic data type (int), we will declare something like the following…
    • int  studMark0, studMark1, studMark2, …, studMark999;

Can you imagine how long we have to write the declaration part by using normal variable declaration?

void main (void)

{  int studMark1, studMark2, studMark3, studMark4, …, …, studMark998, stuMark999, studMark1000;

…

…}

What is Array?

  • An array in C is a fixed-size collection of similar data items stored in contiguous memory locations.
  • It can be used to store the collection of primitive data types such as int, char, float, etc., and also derived and user-defined data types such as pointers, structures, etc.

C Array declaration

  • In C, we have to declare the array like any other variable before using it. We can declare an array by specifying its name, the type of its elements, and the size of its dimensions.
  • When we declare an array in C, the compiler allocates the memory block of the specified size to the array name.
  • data_type array_name [size];
  • or
  • data_type array_name [size1] [size2]…[sizeN];
  • where N is the number of dimensions.

C Array Initialization

  • Initialization in C is the process to assign some initial value to the variable.
  • When the array is declared or allocated memory, the elements of the array contain some garbage value. So, we need to initialize the array to some meaningful value.
  • There are multiple ways in which we can initialize an array in C.
  • In this method, we initialize the array along with its declaration.
  • We use an initializer list to initialize multiple elements of the array.
  • An initializer list is the list of values enclosed within braces { } separated b a comma.
  • data_type array_name [size] = {value1, value2, … valueN};

Array Initialization with Declaration without Size

If we initialize an array using an initializer list, we can skip declaring the size of the array as the compiler can automatically deduce the size of the array in these cases.

The size of the array in these cases is equal to the number of elements present in the initializer list as the compiler can automatically deduce the size of the array.

data_type array_name[] = {1,2,3,4,5};

Types of array in C

  1. One Dimensional array
  2. Two Dimensional array
  3. Multi Dimensional array

One Dimensional Array

One dimensional array is group of variable with single dimension, for example to store the number of days in each month of a year we can have an array of months, such as int months[12];

Syntax:

data_type  arrayname [size];

few variable example:

// single dimensional array

int marks    [10];    // integer array
float weight [5];     // float array
char name    [20];    // char array to store single/multiple character

Example of one dimensional array

# include <stdio.h>
# include <conio.h>
// www.raviroza.com
// 25-Nov-2021, 12.00 pm
void main()
{
	int marks[10];
	int i,n;
        clrscr();

	printf ("Enter Size : ");
	scanf  ("%d",&n);

	for (i=0; i<n; i++)
	{
		printf ("enter [%d] element : ",i+1);
		scanf  ("%d",&marks[i]);
	}
	printf ("\nStored Values in Array \n");
	for (i=0; i<n; i++)
	{
		printf ("[%d] ",marks[i]);
	}
	getch();
}

Output

Output :
Enter Size : 4
enter [1] element : 23
enter [2] element : 90
enter [3] element : 87
enter [4] element : 56

Stored Values in Array
[23] [90] [87] [56]

Two Dimensional array

Two dimensional array is group of rows and columns, where rows represent one dimension and columns represent second dimension, sometimes it is also known as table. For example to store marks of each unit of a given subject, we can have a two-dimensional array such as, int marks[3][4], it will hold marks for 3 subjects and four unit in each subject.

Syntax:

data_type  arrayname [row_size][col_size];
// two dimensional array

int marks    [3][5]; // an array to store marks of 3 subject and 5 units
float weight [2][5];
char cities  [3][10]; // an array to store names of three cities

Example of two dimensional array

# include <stdio.h>
# include <conio.h>
// www.raviroza.com
// 25-Nov-2021, 12.00 pm
void main()
{
	int marks[10][10];
	int r,c,i,j,n;

	printf ("Enter Row Size : ");
	scanf  ("%d",&r);

	printf ("Enter Column Size : ");
	scanf  ("%d",&c);

	for (i=0; i<r; i++)
	{
	    for (j=0; j<c; j++)
        {
            printf ("enter [%d][%d] element : ",i+1,j+1);
            scanf  ("%d",&marks[i][j]);
        }
	}
	printf ("\nStored Values in Mark Array \n");

	for (i=0; i<r; i++)
	{
	    for (j=0; j<c; j++)
        {
            printf ("[%d]  ",marks[i][j]);
        }
        printf ("\n");
	}
	getch();
}

Output:

Enter Row Size : 2
Enter Column Size : 4
enter [1][1] element : 45
enter [1][2] element : 67
enter [1][3] element : 89
enter [1][4] element : 43
enter [2][1] element : 66
enter [2][2] element : 99
enter [2][3] element : 33
enter [2][4] element : 12

Stored Values in Mark Array
[45]  [67]  [89]  [43]
[66]  [99]  [33]  [12]

Multi Dimensional array

Multi dimensional array is also known as array of array. An Array may hold the another array. For example the int multi[2] [3][2]. Now, multi is set of two array consisting of 3 rows and 2 columns in each.

Syntax:

data_type  arrayname [array_size] [row_size][col_size];
// multi dimensional array
//    2 Arrays of -> 3 rows and 4 columns
int x[2]  [3][4] =    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                      11, 12, 13, 14, 15, 16, 17, 18, 19,
                      20, 21, 22, 23};


    // 2 arrays of ->3 rows and 4 columns
int a[2]  [3][4] = {
                      // 1st row        2nd row        3rd row
                  {  {1, 4, 2, 3},   {0, 3, 8, 1}, {2, 2, 3, 2} },   // array 1
                  {  {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }    // array 2
             };

Example of multi dimensional array

# include <stdio.h>
# include <conio.h>
// www.raviroza.com
// 29-Nov-2021, 7.00 pm
void main()
{
        // declare 2-array of 2-rows and 2-columns total 2x2x2=8 elements
	int a[2]   [2][2];

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

	a[1] [0] [0] = 5;
	a[1] [0] [1] = 6;
	a[1] [1] [0] = 7;
	a[1] [1] [1] = 8;


	printf ("0th array from multi-dimensional array \n");
	printf ("%d ", a[0] [0] [0]);
	printf ("%d ", a[0] [0] [1]);
	printf ("%d ", a[0] [1] [0]);
	printf ("%d ", a[0] [1] [1]);

	printf ("\n\n1st array multi-dimensional array \n");
	printf ("%d ", a[1] [0] [0]);
	printf ("%d ", a[1] [0] [1]);
	printf ("%d ", a[1] [1] [0]);
	printf ("%d ", a[1] [1] [1]);

	getch();
}

Output:

0th array from multi-dimensional array
1 2 3 4

1st array multi-dimensional array
5 6 7 8

String Array

  • String is a series of characters that is known as a single data item.
  • C does not support string as data type, though it allows us to define string as char arrays.
  • Group of characters defined with double quotation is a string constant.
syntax:
char string_array_name[size];

example:
char country[10];

Example of two dimension array of string

# include <stdio.h>
# include <conio.h>
// www.raviroza.com
// 03-Dec-2021, Friday
void main()
{
     char cities[10][20];
     int i,n;

     printf("Enter the no. of cities (max.< 10): ");
     scanf("%d",&n);

     for(i=0; i<n; i++)
     {
         printf("Enter %d city name :",i+1);
         scanf("%s",cities[i]);
     }

     printf("\nEntered city names are:\n");
     for(i=0; i<n; i++)
     {
        //puts(cities[i]);
        printf ("%s (%d)",cities[i],strlen(cities[i]));
     }

     getch();
}

Example to find and replace a character in two dimensional string

# include <stdio.h>
# include <conio.h>
# include <string.h>
// www.raviroza.com
// 03-Dec-2021, Friday

void main()
{
     char cities[10][20];
     char find,repl;
     int i,n,k, len, cnt=0;

     printf("Enter the no. of cities (max.< 10): ");
     scanf("%d",&n);

     for(i=0; i<n; i++)
     {
         printf("Enter %d city name :",i+1);
         scanf("%s",cities[i]);
     }

     flushall();
     printf ("Enter char to find : ");
     scanf  ("%c",&find);

     flushall();
     printf ("Enter char to replace with : ");
     scanf  ("%c",&repl);

     printf("\nEntered city names are:\n");
     for(i=0; i<n; i++)
     {
        len = strlen(cities[i]);
        for (k=0; k<len; k++)
        {
            if(cities[i][k] == find)
            {
            // replace the found character
            cities[i][k] = repl;
            // to count the no. of replacement
            cnt++;
            }
            printf ("%c",cities[i][k]);
        }
        printf ("\n");
    }

    printf ("'%c' found & replaced %d times ",find,cnt);
    getch();

}

Output:

Enter the no. of cities (max.< 10): 3

Enter 1 city name : Jamnagar
Enter 2 city name : Rajkut
Enter 3 city name : Baroda

Enter char to find : r
Enter char to replace with : @

Entered city names are :
Jamnaga@
Rajkot
Ba@oda

‘r’ found & replaced '2' times