C-Programming

Arrays

Introduction to array:

It is very time consuming and difficult task for computer to remember a lot of variable names of same type. For example if we have to read 100 different numbers and to display them then we need 100 different variables. This is very tedious task for computer and also consumes a lot of time of the programmer and program will be very lengthy. As a remedy of this type of problem C has a special type of data structure which is called array.  By using array we can give a common name to all the variables of same type. An array is a data structure which allows a collective name to be given to a group of data items of same type but have different subscript. We can recognize the variable by their subscript or index. Array is also called as subscripted data type. An array consists of a series of continuous memory location to store the values. These locations are termed as the element of array.

            An array is a collection of data items of same type sharing a common name but different in their subscript or index.

Note for array:

  1. Array name is common for the entire variable but their index is different.
  2. Array name always referred as the address of the first element and all the accessing the next element is automatically increase the size of data types. For example for int type 2-bytes, for char type 1byte and so on.
  3. It requires continuous memory location to locate or store the variable.

How to declare the array?

Like any other variables, array must be declared before it is being used so that the compiler of the C program understands the type and size of the array used. The general syntax to declare the array is:

data_type array_name[array_size];

Here, data_type represents the type of array, whether the array is of int type or char type or any other.

Array name represents the name of the array as in variable name.

And array size represents the number of the data items that can be stored into the array which is also called dimension of the array which must be an integer number rather than the variable.

For example to store the series:

X1+ X2+ X3+……………………………………..+ Xn

We have not declared n number of variables. It can be represented using array as: x[n]. Examples of declaration of array:

int marks[10];

float temp[15];

char name[10];

Here in the array marks[10],marks is an array of integer type which can store 10 different integer numbers. Similarly in temp[15], which is an array of float type that can store/hold 15 different floating numbers and in name[10] which is an array of character type that can hold 10 alphabets.

Now one question can be created at this instant which is “how the array’s elements are stored in the memory of the computer”?

If we declare an array as int num[10], then it initializes 11 blocks in which 10 blocks are used to store the element of num, and one block is for null character.  If 100 be the memory of the first element of the array then other elements in memory of computer it can be represented as:

100 102 104 106 108 110 112 114 116 118 \0

num[0]   num[1]     num[2]    num[3]    num[4]   num[5]    num[6]   num[7]   num[8]    num[9]   

It should be noted that the position of array’s element always starts from 0 by default however we can alter the position of various array element as our requirement. In the table 100,102,104……………….118 don’t represent the value/content of the array element, it only represents the memory address/location of that element on the computer memory which may vary from computer to computer. And here 100 is the assumed address of primary array element or initial array element. It can be accessed simply by the variable num.

Formula to access the address of next array element:

Address of initial array element + subscript * size of data

For example in the above example, to access the address of 5th array element

num [4]=100+4*2=108;

Where 100 is the address of initial array element, 4 is the subscript for fifth array element and 2 is the size of integer type data type.

 

Types of the array:

There are mainly three types of array on the basis of dimension of the array. They are:

  1. single dimension array
  2. two dimensional array
  3. multidimensional array

  1. single dimensional (1-D) array:

An array whose elements are by a single subscript format is called single dimensional array. That means if an array contains it’s element along only one direction then that type of array is called one dimensional array. This is the simplest form of the array.

The syntax for declaring the one dimensional array is:

Data_type array_name[array_size];

 e.g char name[12];

            int rol[20]; etc.

How to initialize an array?

We can initialize the array element as in the initialization of simple variable in following form:

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

When the computer finds the statement int rol[10], it allocates the 10*2=20 bytes memory for the array and initialize the element to their respective position starting from 0. If 250 be the address of rol[0] then in computer the array element are initializes as:

250 252 254 256 258 260 262 264 266 268  

Address of various array elements

 

1 2 3 4 5 6 7 8 9 10 ‘\0’
Rol[0] Rol[1] Rol[2] Rol[3] Rol[4] Rol[5] Rol[6] Rol[7] Rol[8] Rol[9]  

Values on the respective address of the array

Name of the respective array element variable

 

The C language treats string as an array of character. The size in a character type array represents the maximum number of character that the array can store. It doesn’t mean that the number of character and size of the array should be equal. They may not be equal, but number of characters can not exceed the size of the array. For example:

char name[10];

Declares the name as a character array or name of the string that can hold maximum 10 characters. Suppose we read the following string constant into the string variable name.

“jojolappa”

Here each character of the string is treated as the element of the array name and stores them in the computer memory as:

‘j’ ‘o’ ‘j’ ‘o’ ‘l’ ‘a’ ‘p’ ‘p’ ‘a’ ‘\0’  

When the compiler sees a character string, it terminates it with as additional null character (‘\0’). Thus name [9] or name [10] holds the null character ‘\0’ at the end. When declaring character array, we must allow one extra space for the null terminator.

 

How to read array element?

To read the array element from the keyboard we use looping structure, because we have to repeat the same task for several times. We read the array element in the same way we read the simple variable. Syntax to read the array element from key board:

scanf(“formalstring”,&array_name[position]);

scanf(“%d”,&num[5]);

This statement tells the computer to read an integer and store that in num[5] which is 6th position of the array num.

How to display the array element?

This is also similar to the how we display the simple variable. The general syntax for displaying the array element is:

printf(“formal string”,array_name[position]);

Eg.

printf(“%d”,num[5]);

 

Write a program that read 10 integer numbers and display the entire numbers using array.

#include<stdio.h>

#include<conio.h>

void main()

{

int i,num[10];

for(i=0;i<10;i++)    //to read the numbers

     {

printf(“\nPlease enter %dth number:\t”,i+1);

scanf*”%d”,&num[i]);

     }

clrscr();

//to print the numbers

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

     {

printf(“\n%dth number is %d.”,i+1,num[i]);

     }

getch();

}

 

WRITE A PROGRAM THAT READS ‘n’ NUMBERS AND DISPLAYS THE NUMBERS AND THE SUM AND AVERAGE OF ALL THE NUMBERS.

#include<stdio.h>

#include<conio.h>

void main()

{

int a[100],i, sum=0;

flaot ave;

printf(“\nenter the value of n:\t”);

scanf(“%d”,&n);

//loop to read and sum the array element

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

      {

printf(“\nPlease enter %dth number:   “,i);

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

      sum+=num[i];

      }

ave=(float)sum/n;

//loop to display the array elements

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

      {

printf(“\n%d th number is %d.”,i,num[i]);

      }

printf(“\n\nsum of the array element is %d”,sum);

printf(“\n\nAverage of the array element is %f”,ave);

getch();

}

NOTE:

Do you find any difference in the above two programs while reading the numbers?

There is one difference while reading the array element in the above two programs. The difference is that while reading the number in upper one program there the loop starts from the initialization i=0 and ends when n=0, whereas in the second one program the loop starts from the initialization i=1 and ends when i>n. The first one follows the method to read the elements by default i.e. starting from position 0 but second one does not follows that method. This  is altered method to read the array element. This method is the most often  used.

Write a program which shows that the array stores the element in the continuous memory location.

This program demands to read some numbers store them in array and then display them with their respective address. Here it will be proved that the address is continuous with the difference of the size of data type.

Solution:

#include<stdio.h>

#include<conio.h>

void main()

{

int num[10];

int i;

clrscr();

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

      {

printf(“enter the %dth number:\t”,i);

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

      }

printf(“\n\n\nArray element\t\tValue\t\tAddress\n\n”);

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

printf(“\nNum[%d]\t\t%d\t\t%u”,i,num[i],num[i]);

getch();

}

 

Sample output of the program:

enter the 1th number: 12

enter the 2th number:   32

enter the 3th number:   54

enter the 4th number:   65

enter the 5th number:   34

enter the 6th number:   87

enter the 7th number:   23

enter the 8th number:   99

enter the 9th number:   94

enter the 10th number:  11

 

Array element   Value           Address

 

Num[1]          12              65508

Num[2]          32              65510

Num[3]          54              65512

Num[4]          65              65514

Num[5]          34              65516

Num[6]          87              65518

Num[7]          23              65520

Num[8]          99              65522

Num[9]          94              65524

Num[10]         11              65526

Here in the output of the program, the difference between the address of the each array element is 2 because the size of int type data is 2 bytes, which proves that the array stores the data in continuous memory location. For same data address varies with computer to computer. If you run the same program with same data items you will get different output. This is because computer stores the data where enough space is available.

 

Write a program that reads 10 number and displays from last.

Solution:

#include<stdio.h>

#include<conio.h>

void main()

{

int number[10];

int i;

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

      {

printf(“printf(“\n enter %dth number:\t”,i);

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

      }

clrscr();

printf(“\nNumbers from last:\n\n”);

for(i=n;i>=1;i--)

printf(“%d\t”,number[i]);

getch();

}

 

Write a program that prints the sum of the ‘n’ real numbers entered by the user.

Here real numbers mean the type of data to be read is either float or double.

Solution:

#include<stdio.h>
#include<conio.h>

void main()

{

int i,n;

flaot num[150],sum=0;

clrscr();

printf(“Please enter the value of n:\t”);

scanf(“%d”,&n);

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

      {
printf(“\nenter %dth number:\t”,i);

scanf(“%f”,&num[i]);

sum+=num[i];

      }

printf(“\n\nSum of the entered %d numbers is %f.”,n,sum);

getch();

}

 

  1. Double dimensional (2-D) array:

The arrays which have two dimensions are called two or double dimensional arrays. It means 2-dimensional array contains the data in both x-axis and y-axis or in tabular form where the data are stored in row and column as in matrix. In the one dimensional array there is only one subscript which represents the number of column but in two dimensional array there row as well s column, therefore it requires two subscript in which first one represents the number of rows and second one represents the number of columns. These two dimensional array are widely used in string manipulation and matrix manipulation.

How to declare 2-dimensional array?

 The general syntax for declaring the 2-dimensional array takes the form:

Data_type  array_name[row][column];

Where:

Data_type represents the type of the array

array_name represents the name of the array

row represents the first index; number of rows and

column represents the second index; number of columns.

Now let us an example:

When we declare an array as int num[3][2]; then it indicates there are three rows and 2 columns are available for storing the int type data and there can be stored 3*2=6 data.

The memory location of the array num will be like as:

0                 1

 

   
   
   
0

1

2

 

In the case of 1-dimensional array there is only one index therefore to read and print the data of the array we have to use only one loop, but in the case of 2-dimensional array there are two indices i.e. rows and column therefore we have to use two loops first one for rows and second one for columns.

How to initialize the 2-dimensional array?

Type array_name[no. of rows][no. of columns]={the list of data separating each by comma};

e.g.

int Num[3][4]={1,3,4,5,6,7,3,7,9,5,3,6};

Num[0][0]      Num[0][1]           Num[0][2]            Num[0][3]

 

 

 

 

In the computer memory they stored in continuous memory in tabular form as in the figure shown:

 

1 3 4 5
6 7 3 7
9 5 3 6
Num[0][0]

 

Num[1][0]

 

Num[2][0]

 

Num[2][0]      Num[2][1]           Num[2][2]            Num[2][3]

 

 

 

 

Num[1][0]      Num[1][1]           Num[1][2]            Num[1][3]

 

 

 

 

 

 

 

 

 

 

 

How to access the element of 2-D array?

To read the data:

Scanf(“formal string”,argument);

Eg. scanf(“%d”,&num[1][1]);

To display the data:

Printf(“formal string”,variable);

Eg. printf(“%d”,num[1][1]);

Write a program that reads a matrix of 3*4 and display it in matrix form.

Solution:

#include<stdio.h>

#include<conio.h>

void main()

{

int matrix[3][4];

int i,j;

//loops for reading the matrix

for(i=1;i<=3;i++)       //loop for row

      {

for(j=1;j<=4;j++) //loop for column

      {

printf(“\nplease enter the matrix[%d  %d]:\t”,i,j);

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

      }

      }

printf(“\n\n\nentered matrix is:\n”);

//loops for displaying the matrix

/* since there is new line in each increment of rows, therefore there should taken a new line character in each increment of outer loop.*/

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

      {

printf(“\n”);

      for(j=1;j<=4;j++)

            {

printf(“%d\t”,matrix[i][j]);

            }

      }

getch();

}

Important theory questions:

  1. What do you mean by the term array in C? Explain the need of array variable in C programming.
  2. Write syntax of various types of arrays with suitable examples.
  3. What is an array? List some advantages of subscripted variables.
  4. What do you mean by sorting?

Other programs:

 

 

  1. Design a program to pass 10 different numbers in array and print array value with address.

#include<stdio.h>

#include<conio.h>

void main()

{

int num[10],i;

clrscr();

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

     {

printf(“\netner the %dth number:\t”,i);

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

     }

printf(“\n\n\narray element =value\taddress”);

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

     {

printf(“\nnum[%d]=%d\t%u”,i,num[i],&num[i]);

     }

getch();

}

  1. Write a program to find out the sum the numbers of given list using array.

#include<stdio.h>

#inlcude<conio.h>

void main()

{

int num[100],n,i,sum=0;

clrscr();

printf(“enter the number of terms in the list:\t”);

scanf(“%d”,&n);

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

   {

printf(“\nenter the %dth element:\t”,i);

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

sum=sum+num[i];

   }

printf(“\n\nsum of the given list of numbers is %d.”,sum);

getch();

}

  1. Write a program to calculate the average of n numbers using array.

#inlcude<stdio.h>

#include<conio.h>

void main()

{

int num[100],i,n;

float average;

int total=0;

clrscr();

printf(“\nplease enter the value of n:\t”);

scanf(“%d”,&n);

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

   {

printf(“\nplease enter %dth array element:\t”,i);

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

total+=num[i];

   }

printf(“\n\nhere the entered number list is:\n”);

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

printf(“%d\t”,num[i]);

average=(flaot)total/n;

printf(“\nthe average value of the given list is:%f”,average);

getch();

}

  1. Write a program to pass 7 days temperature and calculate average temperature, maximum temperature and minimum temperature using array.

#include<stdio.h>

#include<conio.h>

void main()

{

float temp[7], max,min,net=0;

flaot ave;

int i;

clrscr();

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

   {

printf(“\nplease enter %dth day\’s temperature:\t”,i);

scanf(“%f”,&temp[i]);

net+=temp[i];

   }

ave=net/7;

max=min=temp[1];

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

   {

if(temp[i]>max)

max=temp[i];

if(temp[i]<min)

min=temp[i];

   }  

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

printf(“the average temperature of the week is %f.”,ave);

printf(“\nthe maximum temperature is %f.”,max);

printf(“\nthe minimum temperature of the week is %f.”,min);

getch();

}

 

  1. Write a program to input student name, roll no., and total marks obtained by the student for your class then generate the merit list.

#include<stdio.h>

#include<conio.h>

void main()

{

char name[50][25],temp1[25];

int n,roll[50],marks[50],temp2;

int i,j,n;

clrscr();

printf(“etner the number of students in your class:\t”);

scanf(“%d”,&n);

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

     {

printf(“enter the name of the %dth student:\t”,i);

scanf(“%s”,name[i]);

printf(“enter the roll number:\t”);

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

printf(“enter the marks obtained:\t”);

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

}

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

     {

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

     {

if(marks[i]<marks[j])

     {

//exchanging the marks

temp2=marks[i];

marks[i]=marks[j];

marks[j]=temp2;

//excahanging the roll number

temp2=marks[i];

marks[i]=marks[j];

marks[j]=temp;

//exchanging the name

strcpy(temp1,name[i]);

strcpy(name[i],name[j]);

strcpy(name[j],temp);

     }

}

}

clrscr();

printf”\t\t\tmerit list”);

printf(“\nroll no.\tname\tmarks”);

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

     {

printf(“\n%d\t%s\t\t%d”,roll[i],name[i],marks[i]);

     }

getch();

}

  1. Write a program to search a given number from the list of n numbers.

#inlcude<stdio.h>

#include<conio.h>

#include<stdlib.h>

void main()

{

int num[100],i,j,n;

int search,temp;

printf(“enter the number of terms in the list:\t”);

scanf(“%d”,&n);

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

   {

printf(“\nenter the %dth number:\t”);

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

   }

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

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

   if(num[i]>num[j])

        {

temp=num[i];

num[i]=num[j];

num[j]=temp;

        }

printf(“\n\nplease enter the number to be searched in the list:\t”);

scanf(“%d”,&search);

printf(“\nthe entered number list is:\n”);

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

printf(“%d\t”,num[i]);

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

   {

if(search==num[i])

   {

printf(“\nthe entered number is in the list at the position of %d.”,i);

getch();

exit(0);

   }

}

if(i==n)

printf(“\n\nsorry, the entered number is not in the given number list.);

getch();

}

Some important theory questions for the final examination (Prev Lesson)
(Next Lesson) C Programming Questions Solutions with Arrays
Back to C-Programming

No Comments

Post a Reply

Teacher
Bhim Gautam
Role : Lecturer
Read More
error: Content is protected !!