Chapter 8

 

Array

 

 

The programs that we have developed so far used basic data types namely int, float, char and variations of int and float. Although, these data types are very useful, they have some limitations. A variable of these types can store only one value at a given time. Many applications require the processing of multiple data items that have common characteristics. To do so using basic data types we have to declare number of variables with different names. For example to store the age of 10 employees, we will have to declare 10 variables individually to store these 10 data. In this situation it is often convenient to place the data items into one unit such that it is easier to read, process, and print. To facilitate efficient storage, access, and manipulation of data items, C provides a powerful data type known as array.

An array is a sequence of data of same type, which occupies successive memory location. For example, 10 integer numbers stored by same name and with different subscript. In brief, an array is used to hold/store similar type of data. 

Each array element is referred to by specifying the array name followed by one or more subscripts, with each subscript enclosed in square brackets. Each subscript must be expressed as a non-negative integer. In an n-element array, the array elements are x[0], x[1], x[2], ........., x[n-1], as illustrated in figure below.

 

x[0]

x[1]

x[2]

 

x[n-2]

x[n-1]

Fig: x in an n-element, one-dimensional array


There are three types of arrays:

  • One-Dimensional Arrays
  • Two-Dimensional Arrays
  • Multidimensional Arrays

           One Dimensional Array

An array with only one subscript is known as one dimensional array. One dimensional array can be compared with a matrix with either a single row or column. One dimensional array has either a length or breadth. Figure below represents one dimensional array.

 


 Declaration of one-dimensional array

data type name of the array [size of the array];

Example: int x[10];

This declaration reserves 10 successive memory locations to hold 10 integer type of data.

 

Accessing one-dimensional array

To access a particular location of an array, specify the array name, followed by square bracket with index number inside it. The numbering of index of C array starts with 0 and ends at n-1, where n is the size of the array.

 

//To store integer numbers in an array and print them (1 dimension)

 

#include<stdio.h>

void main( )

{

      int x[10] = {5,8,9,45,10,-2,0,-7,6,8}, i;

     

      printf("\n Here are the 10 integer numbers in the array");

      for(i=0; i<10; i++)

            printf("\n%d", x[i]);

}

 

 

 

Example: Program to take value of 10 numbers and assign it to array and later print them.

#include<stdio.h>

#include<conio.h>

void main()

      {

      int marks[10],i;

            for(i=0; i<10; i++)

            {

            printf("\n Enter marks obtained for student %d", i);

            scanf("%d", &marks[i]);

            }

            for(i=0; i<10; i++)

            {

            printf("\n %d", marks[i]);

            }

      }

 

# Initialization of Array

At the time of declaration array can be initialized with values as shown below:

int age[5]={10,15,25,30,13};

 

Note:

We can define an array to be initially very big then ask the user for the size of the array, store the user value in some variable and use the variable as the upper index of the array.

Example:

#include<stdio.h>

#include<conio.h>

void main()

      {

      int marks[100],n, i;

      printf("\n Enter size of the matrix:');

      scanf("%d", &n);

      for(i=0; i<n; i++)

                        {

                  printf("\n Enter the value:");

            scanf("%d", &marks[i]);

            }

            }

 

 

Sorting of Array

Sorting is the process of arranging data in an array in ascending or descending order. There are two algorithms which can be implemented to sort an array:

Ø  Bubble Sort

Ø  Selection Sort

Bubble Sort

 

This algorithm begins by comparing the first item of the array with the next and swap takes place if necessary as shown in figure below. In the first pass (in case of ascending order) largest element is placed at the end of the array. In the second pass, the second largest element is placed before the largest element of the array as shown in figure below. In bubble sort, if there are n elements to be sorted, it will take n-1 pass to sort entire element.



//Program to sort the given elements using bubble sort algorithm

#include<stdio.h>

#include<conio.h>

void main()

      {

            int data[100], temp, pass, n, i;

            printf("\n Enter number of data:");

            scanf("%d", &n);

            for(i=0; i<n; i++)

            {

                  printf("\n Enter data:");

                  scanf("%d", &data[i]);

            }

                  for(pass=0; pass<n-1; pass++)

                  {

                        for(i=0; i<n-1-pass; i++)

                        {

                              if(data[i]>data[i+1])

                              {

                              temp=data[i];

                              data[i]=data[i+1];

                              data[i+1]=temp;

                              }

                        }

                  }

                  printf("\n Sorted data...");

                  for(i=0; i<n; i++)

                  {

                  printf("\n %d", data[i]);

                  }

      getch();

            }

 

 

 

 

 

/*To sort a list of 5 integer numbers in ascending order.*/

 

#include<stdio.h>

#include<conio.h>

#define k 5

 

   void main()

   {

      int x[k],i;

      clrscr();

      printf("\n Enter any 5 integer nos. to be sorted");

         for(i=0;i<5;i++)

            scanf("%d", &x[i]);

         for(i=0;i<4;i++)

         {

            for(k=0;k<5;i++)

            {

                  if(x[i]>x[k])

                  {

                  temp=x[i];

                  x[i]=x[k];

                  x[k]=temp;

                  }

            }

         }

         printf("\n");

  

            for(i=0;i<5;i++)

            {

                  printf("\n %d", x[i]);

            }

      getch();

   }

 

 

 

 

 

 

 

 

 

 

 

 

 

Selection Sort

 

The main idea behind the selection sort is to find the smallest element and place it on its final position in each pass. This algorithm starts by comparing the first element with the second element and swapping takes place if necessary as shown in figure below. In the first pass, the smallest element is placed at the top of the array. In the second pass, second smallest element is placed after the smallest element of the array as shown in the figure below and so on. In selection sort also, if there are n elements to be sorted, it will take n-1 pass to sort entire elements.

//Program to sort elements of array using selection sort algorithm

#include<stdio.h>

#include<conio.h>

void main()

      {

            int data[100], n, pass, temp, i;

            clrscr();

            printf("\n Enter number of data:);

            scanf("%d", &n);

                  for(i=0; i<n; i++)

                  {

                        printf("\n Enter data:");

                        scanf("%d", &data[i]);

                  }

                  for(pass=0; pass<n-1; pass++)

                  {

                        for(i=pass; i<n; i++)

                        {

                              if(data[pass]>data[i])

                              {

                              temp=data[pass];

                              data[pass]=data[i];

                              data[i]=temp;

                              }

                        }

                  }

                  printf("\n Sorted list........");

                  for(i=0; i<n; i++)

                  {

                  printf("\n %d", data[i]);

                  }

      getch();

      }

 

 

 

 

 

#Finding the biggest or smallest among elements of array

To find the biggest or smallest among elements of array we first assume the biggest or smallest number to be the first element of the array then compare it with every element of the array and correcting the assumption as we compare.

Example: Finding the biggest among the elements of the array

#include<stdio.h>

#include<conio.h>

void main()

      {

            int data[100], n, big, i;

            clrscr();

            printf("\n Enter the number of elements:");

            scanf("%d", &n);

            for(i=0; i<n; i++)

            {

            printf("\n Enter the data:");

            scanf("%d", &data[i]);

            }

            big=data[0];

            for(i=1; i<n; i++)

            {

                  if(data[i]>big)

                  big=data[i];

            }

      printf("\n The biggest number of the array is %d", big);

      getch();

      }

 

Two-dimensional Array

The arrays we have used so far have been one-dimensional. That is, the elements of the array could be represented either as a single column or a single row. When dealing with one-dimensional arrays, we specify a single subscript to locate a specific element. Two dimensional arrays are array with both rows and column and we have to specify two subscripts inside square brackets to locate a specific element.

#Declaration of two dimensional arrays

data type name of the array [size of row][size of column];

int x[5][5];

 

#Accessing Two dimensional array

To access a particular location of two-dimensional array, specify the array name followed by two square brackets with row and column number inside it.

//To store numbers in a two dimensional array and print them

 

#include<stdio.h>

#include<conio.h>

void main()

{

int a[3][3]={1,2,3,4,5,6,7,8,9},       b[3][3]={1,2,3,4,5,6,7,8,9},c[3][3],i, j;

clrscr();

for(i=0;i<3;i++)

{

                  for(j=0;j<3;j++)

                  {

                  printf("\t %d", a[i][j]);

                  }

            printf("\n");

}

printf("\n");

for(i=0;i<3;i++)

{

                  for(j=0;j<3;j++)

                  {

                  printf("\t %d", b[i][j]);

                  }

            printf("\n");

}

printf("\n");

for(i=0;i<3;i++)

{

            for(j=0;j<3;j++)

            {

            c[i][j]=a[i][j]+b[i][j];

            }

      printf("\n");

}

for(i=0;i<3;i++)

{

      for(j=0;j<3;j++)

      {

            printf("\t %d", c[i][j]);

      }

      printf("\n");

}

}

Example: Program to input values into two dimensional arrays and print it.

#include<stdio.h>

#include<conio.h>

void main()

      {

      int data[5][5], i, j;

      for(i=0; i<5; i++)            //outer for loop for row of the array

      {

            for(j=0; j<5; j++)      //inner for loop for column of the array

            {

                  printf("\n Enter value for data[%d][%d]:", i, j);

                  scanf("%d", &data[i][j]);

            }

      }

      for(i=0; i<5; i++)

      {

            for(j=0; j<5; j++)

            {

                  printf("%4d", data[i][j]);

            }

            printf("\n");

      }

      getch();

      }

Initialization of two-dimensional array

In the time of declaration two dimensional arrays can be initialized as shown:

int data[2][5]={{4,5,6,7,8}, {12,34,56,54,32}};

 

Note

We can define size of the two dimensional array to be very large then ask the user order of the array, i.e. size of row and column.

 

 

 

 

 

Example: Program to input values into two dimensional arrays and print it.

 

#include<stdio.h>

#include<conio.h>

void main()

      {

      int data[5][5], i, j, row, column;

      printf("\n Enter order of the matrix:");

      scanf("%d %d", &row, &column);

      for(i=0; i<row; i++)          //outer for loop for row of the array

            {

            for(j=0; j<column; j++) //inner for loop for column of the array

                  {

                  printf("\n Enter value for data[%d][%d]:"i, j);

                  scanf("%d", &data[i][j]);

                  }

            }

      for(i=0; i<row; i++)

            {

            for(j=0; j<column; j++)

                  {

                  printf("%4d", data[i][j]);

                  }

            printf("\n");

            }

      getch();

      }

 

Two dimensional array are used to solve the matrix problem

 

 

 

 

 

 

 

Example: Addition of two matrixes

#include<stdio.h>

#include<conio.h>

void main()

{

int a[10][10], b[10][10], c[10][10], i, j, row, column;

clrscr();

printf("\n Enter the row length:");

scanf("%d", &row);

printf("\n Enter the column breadth:");

scanf("%d", &column);

for(i=0; i<row; i++)

      {

            for(j=0; j<column; j++)

            {

            printf("\n Enter value for cell a[%d][%d] for matrix A:", i, j);                  scanf("%d", &a[i][j]);

            }

      }

for(i=0; i<row; i++)

      {

            for(j=0; j<column; j++)

            {

            printf("\n Enter value for cell b[%d][%d] for matrix B:",i,j);               scanf("%d", &b[i][j]);

            }

      }

for(i=0; i<row; i++)

      {

            for(j=0; j<column; j++)

            {

            c[i][j]=a[i][j]+b[i][j];

            }

      }

for(i=0; i<row; i++)

      {

            for(j=0; j<column; j++)

            {

            printf("%4d ", c[i][j]);

            }

      printf("\n");

      }

getch();

}

 

 

 

 

 

 

 

Example: Matrix Multiplication

#include<stdio.h>

#include<conio.h>

void main()

      {

      int a[10][10], b[10][10], c[10][10], i, j, k;

int a_row, b_row, a_col, b_col;

      clrscr();

      printf("\n Enter number of row and column of Matrix A:");

      scanf("%d %d", &a_row, &a_col);

      printf("\n Enter number of row and column of Matrix B:");

      scanf("%d %d", &b_row, &b_col);

            if(a_col==b_row)

            {

            printf("\nEnter value of Matrix A:");

            for(i=0; i<a_row; i++)

            {

                  for(j=0; j<a_col; j++)

                  {

                        printf("\n Enter value of A[%d][%d]:", i, j);

                        scanf("%d", &a[i][j]);

                  }

            }

            for(i=0; i<b_row; i++)

            {

                  for(j=0; j<b_col; j++)

                  {

                        printf("\n Enter value of B[%d][%d]:", i,j);

                        scanf("%d", &b[i][j]);

                  }

            }

            for(i=0; i<a_row; i++)

            {

                  for(j=0; j<a_col; j++)

                  {

                        c[i][j]=0;

                        for(k=0; k<a_col; k++)

                        {

                              c[i][j]=c[i][j]+a[i][k]*b[k][j];

                        }

                  }

            }

            printf("\n\nMatrix A...........\n");

            for(i=0; i<a_row; i++)

            {

                  for(j=0; j<a_col; j++)

                  {

                        printf("%4d", a[i][j]);

                  }

                  printf("\n");

            }

            printf("\n\nMatrix B...........\n");

            for(i=0; i<b_row; i++)

            {

                  for(j=0; j<b_col; j++)

                  {

                        printf("%4d", b[i][j]);

                  }

                  printf("\n");

            }

            printf("\n\nMatrix C...........\n");

            for(i=0; i<a_row; i++)

            {

                  for(j=0; j<b_col; j++)

                  {

                        printf("%4d", c[i][j]);

                  }

                  printf("\n");

            }

            }

      else

            {

            printf("\nMatrix multiplication is not possible...");

            }

      getch();

      }

 

Example: Program to find trace of the matrix (Sum of the diagonal element of matrix)

#include<stdio.h>

#include>conio.h>

void main()

      {

      int data[10][10], row, column, i, j, sum=0;

      printf("\n Enter order of the matrix:");

      scanf("%d %d", &row, &column);

            for(i=0; i<row; i++)

            {

                  for(j=0; j<column; j++)

                  {

                  printf("\n Enter value for data[%d][%d]:", i, j);

                  scanf("%d" &data[i][j]);

                  }

            }

            for(i=0; i<row; i++)

            {

                  for (j=0; j<column; j++)

                  {

                        if(i==j)

                        {

                        sum=sum+ data[i][j];

                        }

                  }

            }

      printf("\n The trace of the matrix is %d", sum);

      getch();

      }

Suppose there are three batsman and they played three cricket matches. Their scored runs are tabulated in the table given below.

 

Match 1

Match 2

Match 3

Batsman 1

65

53

78

Batsman 2

32

53

24

Batsman 3

63

80

95

 

 

 

 

 #include<stdio.h>

#include<conio.h>

void main()

{

int runs[3][3],i, j, sum=0;

float avg;

      for(i=0;i<3;i++)

{

for(j=0;j<3;j++)

{

printf(‘Enter the run in match %d by Batsman %d:\n”, i+1,j+1);

scanf(“%d”, &runs[i][j]);

}

printf(”\n”);

}

for(i=0;i<3;i++)

{

for(j=0;j<3;j++)

{

sum=sum+ runs[i][j];

}

avg=(float)sum/3;

printf(“Batsman %d has scored %d with average %.2f\n”,i+1,sum,avg);

avg=0.0;

sum=0;

}

getch();

}

Multidimensional Array

The array with more than two dimensions is called as multidimensional array. The general format for declaring a multidimensional array is as follows.

Data type name [d1][d2]…[dn]

The array name is defined to contain d1*d2*….dn elements of the specific type where d1, d2,…..dn are constants. For example, int three-D [4][2][10];

Defines three dimensional arrays, three-D containing 80 integers.

 

Multidimensional array can be initialized in the same manner as one- dimensional array containing 4 rows and 3 columns.

int matrix [4][3]={ {1,2,3},{4,5,6},{7,8,9}};

The elements in the fourth row are set to 0 since no values are specified for that row.

 

/*Program to illustrate the multi dimensional array. This program prepares the mark-Sheet of the 2 students with their marks in 2 terminals exams with 5 subject each and calculate the average internal marks and total in each terminals*/

 

#include<stdio.h>

#define TERM 2

#define STUDENTS 2

#define SUB 5

void main()

{

int marks[TERM][STUDENTS][SUB];

int i, j, k, total=0,temp=0;

float avg=0.0;

clrscr();

printf(“St. Xavier’s College”);

printf(“--------------------------------‘);

for(i=0; i<TERM; i++)

{    

for(j=0;j<STUDENTS; j++)

{

for(k=0;k<SUB; k++)

{

printf(“Enter the marks of terminal %d/student%d/subject%d\n”,i+1,j+1,k+1);

scanf(“%d’,&marks[i][j][k]);

}

            }

      }

printf(“\t\t\t Marks Sheet\n”);

printf(“\n-----------------------------“);

printf(“\n TERMINAL STUDENT SUB1 SUB2 SUB3 SUB4 SUB5 TOTAL AVG\n”);

      for(i=0; i<TERM; i++)

{    

for(j=0;j<STUDENTS; j++)

{

printf(“\n--------------------------------\n”);

printf(“\n %5d%7d”,i+1,j+1);

 

for(k=0;k<SUB; k++)

{

printf(“%8d”,marks[i][j][k]);

total+=marks[i][j][k];

                  }

            printf(“%7d”,total);

temp+=total;

total=0;

avg=(float) temp/SUB;

printf(“%9.2f\n”,avg);

temp=0;

}

printf(“\n”);

}

printf(“\n--------------------------------------------\n”);

getch();

}

  Full Width


 




Post a Comment

0 Comments