7 Data Structure: Array – Programming in C, 3/e, 3rd Edition

CHAPTER 7

Data Structure: Array

Chapter Outline
7.1  INTRODUCTION

An array is a very popular and useful data structure used to store data elements in successive memory locations. More than one element is stored in a sequence, so it is also called a composite data structure. An array is a linear and homogeneous data structure. An array permits homogeneous data. It means that similar types of elements are stored contiguously in the memory and that too under one variable name. It can be combined with a non-homogeneous structure, and a complex data structure can be created. We know that an array of structure objects can also be useful. An array can be declared of any standard or custom data type. The array of character (strings) type works somewhat differently from an array of integers, floating numbers.

Consider the following example. A variable a having datatype integer is initially assigned some value and later on its value is changed. Later assigned value to the variable can be displayed.

 

void main()

{

int a=2;

a=4;

printf(“%d”,a);

}

OUTPUT:

4

In the above example, the value of a printed is 4. 2 is assigned to ‘a’ before assigning 4 to it. When we assign 4 to a then the value stored in ‘a’ is replaced with the new value. Hence, ordinary variables are capable of storing one value at a time. This fact is the same for all the data types. But in numerous applications variables must be assigned more than one value. This can be obtained with the help of arrays. An array variable allows the storing of more similar data type elements/values at a time.

7.2  ARRAY DECLARATION

Declaration of a one-dimensional array can be done with data type first, followed by the variable name and lastly the array size is enclosed in square brackets. Array size should be integer constant and it must be greater than zero and data type should be valid C data type.

For example, declaration of one-dimensional array is as follows:

int a[5]; It tells the compiler that ‘a’ is an integer type of an array and its size is five integers. The compiler reserves 2 bytes of memory for each integer array element, i.e. 10 bytes are reserved for storing five integers in the memory. In the same way, an array of differrant data types is declared as follows:

 

char ch[10];

float real[10];

long num[5];

When we declare a variable, for example:

 

int x;

the variable x is declared and the memory location of two bytes is allocated to it and later a single value can be stored in it as shown in Figure 7.1

 

x=4;

Figure 7.1  Variable mechanisms

Every variable has a name, a value assigned to it and it is to be stored in memory location. Hence, from the above, we can say that only one value is assigned to a variable or stored.

The way, we declare one-dimensional array in the same way and can also declare two-dimensional array. Two-dimensional array is a table that contains rows and columns. For Example, int a[3][3]; It informs the compiler that ‘a’ is an integer type of an array and its size is 9 integers. This array is a three-by-three matrix. Its details are given in the two-dimensional array and operations.

Similarly, one can declare the multi-dimensional array as follows: datatype arrayname[size1][size2][size3]--------[sizeN];

For example, the following array declares three-dimensional array: int a[3][3][3];

Its details are given in this chapter under three-or multi-dimensional array title.

7.3  ARRAY INITIALIZATION

The array initialization can be done as under:

 

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

Here, five elements are stored in an array ‘a’. List of elements initialized is shown within the braces. The array elements are stored sequentially in separate locations. Then, the question arises how to call individually to each element from this bunch of integer elements. Reading of the array elements begins from ‘0’. By indicating the position of elements, one can retrieve any element of an array. Array elements are called with array names followed by the element numbers. Table 7.1 explains the same.

Table 7.1  Calling array elements

a[0] refers to 1st element i.e. 1

a[1] refers to 2nd element i.e. 2

a[2] refers to 3rd element i.e. 3

a[3] refers to 4th element i.e. 4

a[4] refers to 5th element i.e. 5

Example:

To store more than one value the programming languages have an in-built data structure called an array.

  1. int num[5];

    In the above declaration, an integer array of five elements is declared. Memories for five integers, i.e. successive 10 bytes, are reserved for the num array. To initialize the num array following syntax can be used.

  2. int num[5] = {1,2,4,2,5};

    In the above statement, all elements are initialized. It is also possible to initialize individual element by specifying the subscript number in the square bracket following the array name.

    Array elements are accessed as follows:

     

    num[0]=1;

    num[1]=2;

    num[2]=4;

    num[3]=2;

    num[4]=5;

The initialization can be done at the compile time or dynamically at the run time. The above is an example of compile time initialization. In the statement (2), declaration and initialization are done at once; in such type of declaration the number of elements (five) is not necessary to mention in the square bracket []. The compiler automatically counts the value initialized and assumes the number of elements initialized as the array size.

In the above array, the element num[0] i.e. 1 is the lowest bound and num[4] i.e. 5 is the last element. In C and C++, there is no bound checking. Hence, the programmer has to check it while accessing or storing elements. Once the array is declared, its lowest bound cannot be changed but the upper bound can be expanded. The array name itself is a constant pointer, and therefore we cannot modify it. Storing elements in contiguous memory locations can expand the upper bound.

The array name itself is a pointer. The array num is pointer to the first element i.e. num contains address of memory location where element 1 is stored. The address stored in the array name is called the base address. Figure 7.2 shows the pictorial representation. To access individual elements, the following syntax is used.

Figure 7.2  Array of integers

num[0] refers to the 1

num[1] refers to the 2

num[2] refers to the 4

num[3] refers to the 2

num[4] refers to the 5

Thus, an array is a collection of elements of the same data type, stored in unique and successive memory locations.

7.4  ARRAY TERMINOLOGY

Size: Number of elements or capacity to store elements in an array is called its size. It is always mentioned in brackets ([]).

Type: Types refer to data type. It decides which type of element is stored in the array. It also instructs the compiler to reserve memory according to data type.

Base: The address of the first element (0th) is a base address. The array name itself stores address of the first element.

Index: The array name is used to refer to the array element. For example, num[x], num is array name and x is index. The value of x begins from 0 to onwards depending on the size of the array. The index value is always an integer value.

Range: Index of an array i.e. value of x varies from lower bound to upper bound while writing or reading elements from an array. For example, in num[100], the range of index is 0 to 99.

Word: It indicates the space required for an element. In each memory location, computer can store a data piece. The space occupation varies from machine to machine. If the size of element is more than word (one byte) then it occupies two successive memory locations. The variables of data type int, float, long need more than one byte in memory.

7.5  CHARACTERISTICS OF AN ARRAY
  1. The Declaration int a[5] is nothing but creation of five variables of integer types in memory. Instead of declaring five variables for five values, the programmer can define them in an array.
  2. All the elements of an array share the same name, and they are distinguished from one another with the help of the element number.
  3. The element number in an array plays a major role for calling each element.
  4. Any particular element of an array can be modified separately without disturbing the other elements.

     

    int a[5]={1,2,3,4,8};

    If a programmer needs to replace 8 with 10, then it need not require changing all other numbers except 8. To carry out this task, the statement a[4]=10 can be used. Here, other four elements are not disturbed.

  5. Any element of an array a[] can be assigned/equated to another ordinary variable or array variable of its type.

    Example:

    b= a[2];

    a[2]=a[3];

    1. In the statement b=a[2] or vice versa, the value of a[2] is assigned to ‘b’, where ‘b’ is an integer.
    2. In the statement a[2]=a[3] or vice versa, the value of a[2] is assigned to a[3], where both the elements are of the same array.
    3. The array elements are stored in continuous memory locations.
  6. Array elements are stored in contiguous memory locations.

    A program on array initialization and determination of their memory locations is given below:

    7.1  Write a program to display array elements with their addresses.

     

    int main()

    {

    int num[5]={1,2,3,2,5};

    clrscr();

    printf(“\n num[0] = %d Address : %u”,num[0],&num[0]);

    printf(“\n num[1] = %d Address : %u”,num[1],&num[1]);

    printf(“\n num[2] = %d Address : %u”,num[2],&num[2]);

    printf(“\n num[3] = %d Address : %u”,num[3],&num[3]);

    printf(“\n num[4] = %d Address : %u”,num[4],&num[4]);

    return 0;

    }

    OUTPUT:

    num[0] = 1 Address : 65516

    num[1] = 2 Address : 65518

    num[2] = 3 Address : 65520

    num[3] = 2 Address : 65522

    num[4] = 5 Address : 65524

    Explanation:

    In the output of the program, elements and their addresses are displayed. Recall that integer requires two bytes in memory. Hence, the memory locations displayed at the output have a difference of two. From the above program, it is clear that array elements are stored in contiguous memory locations. Figure 7.3 shows the memory location and values stored.

    Figure 7.3  Storage of one-dimensional array

  7. Once the array is declared, its lowest boundary cannot be changed but upper boundary can be expanded. The array name itself is a constant pointer and we cannot modify it. Therefore, the lowest boundary of an array cannot be expanded. In other words, even if the boundary exceeds than specified, nothing happens. The compiler throws no errors.

    The reader can execute the following program for verifying the above concept.

    7.2  Write a program to exceed the upper boundary of an array and see the element after expansion of an array.

     

    void main()

    {

    int num[5]={1,2,3,2,5};

    num[5]=6;

    clrscr();

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

    getche();

    }

    OUTPUT:

    Num[5]=6

    Explanation:

    In the above program, array num[5] is declared with array size 5 and it is initialized with 5 elements. In the next statement, 6th element is also initialized and displayed. Hence, we can say that upper boundary of an array can be expanded.

  8. We know that an array name itself is a pointer. Though it is a pointer, it does not need ‘*’ operator. The brackets ([]) automatically denote that the variable is a pointer.
  9. All the elements of an array share the same name, and they are distinguished from one another with the help of the element number.
  10. The amount of memory required for an array depends upon the data type and the number of elements. The total size in bytes for a single dimensional array is computed as shown below:

     

    Total bytes=sizeof(data type) X size of array

     

  11. The operation such as insertion, deletion of an element can be done with the list but cannot be done with an array. Once an array is created, we cannot remove or insert memory location. An element can be deleted, replaced but the memory location remains as it is.
  12. When an array is declared and not initialized, it contains garbage values. If we declared an array as static, all elements are initialized to zero. However, the values of static type data persist and remain in the memory as long as program executes. To overcome this problem, initialize first element of an array with zero or any number. Remaining all elements are automatically initialized to zero, provided the initialization is done in the declaration statement of an array. The following program illustrates this.

    7.3  Write a program to initialize the static array and display its elements.

     

    void main()

    {

    int num[5]={0},j;

    clrscr();

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

    printf(“\nnum[%d]=%d”,j,num[j]);

    getche();

    }

    OUTPUT:

    num[0]=0

    num[1]=0

    num[2]=0

    num[3]=0

    num[4]=0

    Explanation:

    In the above program, an array num[5] is declared and the first element is initialized with zero. The compiler automatically initializes all elements with zero. Using the for loop the contents of an array are displayed and we can see that all elements have zero values.

7.6  ONE-DIMENSIONAL ARRAY

Array elements are stored contiguously in sequence one after the other. The elements of an array are just arranged in one-dimension. They can be shown in a row or column. Single subscript will be used in one-dimensional array to represent its elements.

An example of initialization of an array: − int a[5]; in this initialization of an array is done. The type of variable is integer; its variable name is a and 5 is the size of the array.

The elements of the integer array a[5] are stored in contiguous memory locations. It is assumed that the starting memory location is 2000. Each integer element requires 2 bytes. Hence, subsequent element appears after the gap of two locations. Table 7.2 shows the locations of elements of integer array.

Table 7.2  Integer data type and their memory locations

Similarly, the elements of arrays of any data type are stored in contiguous memory location. The only difference is that the number of locations is different for different data types.

An example is illustrated below on the basis of this point.

7.4  Write a program to print bytes reserved for various types of data and space required for storing them in memory using arrays.

 

void main()

{

int i[10];

char c[10];

long l[10];

clrscr();

printf(“The type ‘int’ requires %d Bytes”,sizeof(int));

printf(“\nThe type ‘char’ requires %d Bytes”,sizeof(char));

printf(“\nThe type ‘long’ requires %d Bytes”,sizeof(long));

printf(“\n %d memory locations are reserved for ten ‘int’ elements”,sizeof(i));

printf(“\n %d memory locations are reserved for ten ‘char’ elements”,sizeof(c));

printf(“\n %d memory locations are reserved for ten ‘long’ elements”,sizeof(l));

}

OUTPUT:

The type ‘int’ requires 2 Bytes

The type ‘char’ requires 1 Bytes

The type ‘long’ requires 4 Bytes

20 memory locations are reserved for ten ‘int’ elements

10 memory locations are reserved for ten ‘char’ elements

40 memory locations are reserved for ten ‘long’ elements

Explanation:

The sizeof() function provides the size of data type in bytes. In the above example, int, char and long type of data variables are supplied to this function which gives the results 2, 1 and 4 bytes, respectively. The required number of memory locations for int, char and long will be 2, 1 and 4. Memory locations required for the arrays = argument of an array × sizeof(data type). In the above example, an array int i[10] requires 20 memory locations, since each element requires two memory locations. Memory requirement for various data types will be as given in Table 7.3.

Table 7.3  Data type and their required bytes

Data Type

Memory Requirement

char

1 bytes

int

2 bytes

float

4 bytes

long

4 bytes

double

8 bytes

Character arrays are called strings. There is a slight difference between an integer array and character array. In character array, NULL (‘\0’) character is automatically added at the end, whereas in integer or other types of arrays, no null/character is placed at the end.

The NULL character acts as the end of the character array. By using this NULL character compiler detects the end of the character array. When compiler reads the NULL character ‘\0’, there is end of character array.

Note: Detailed information about strings (character array) is given in another chapter ‘Strings and Standard functions.’ The explanation about strings is given in brief in this chapter.

Given below is an example of a string.

7.5  Write a program to display character array with their address.

 

void main()

{

char name[10]={‘A’,’R’,’R’,’A’,’Y’};

int i=0;

clrscr();

printf(“\n Character Memory Location \n”);

while(name[i]!=‘\0’)

{

  printf(“\n [%c]\t\t [%u]”,name[i],&name[i]);

    i++;

}

}

OUTPUT:

Character
Memory Location
[A]
4054
[R]
4055
[R]
4056
[A]
4057
[Y]
4058

Explanation:

The elements of an array are stored in contiguous memory locations. In the above example, elements of one-dimensional array ‘A’,‘R’,‘R’,‘A’,‘Y’ are stored from location 4054 to 4058.

One-dimensional character array elements will be stored in memory as per Table 7.4

Table 7.4  Character array elements and their locations

Notes: In case a NULL ‘\0’ is initialized in the above example after ‘Y’, the result displayed will be ‘ARRAY’.

A few programs are provided on one-dimensional array and they are as follows:

7.6  Write a program to add even and odd numbers from 1 to 10. Store them and display their results in two separate arrays.

 

void main()

{

int sumo=0,sume=0,i=0,odd[5],even[5],a=-1,b=-1;

clrscr();

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

{

  if(i%2==0)

  even[++a]=i;

  else

  odd[++b]=i;

}

printf(“\n\tEven \t\tOdd”);

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

{

  printf(“\n\t %d\t\t %d”,even[i],odd[i]);

  sume=sume+even[i];

  sumo=sumo+odd[i];

}

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

printf(“Addition: %d %14d”,sume,sumo);

}

OUTPUT:

Even
Odd
2
1
4
3
6
5
8
7
10
9
==========================
Addition: 30
25

Explanation:

The for loop executes 10 times. In the for loop, the value of loop variable ‘i’ is tested for ‘even’ and ‘odd’ conditions. If the value of ‘i’ is even then it is assigned to array even[]otherwise to odd[]. Thus, for 10 times this task is performed. Finally, the second for loop displays both the even[] and odd[] arrays. In the same array, sum of even and odd elements is calculated and displayed.

7.7  Write a program to input five numbers through the keyboard. Compute and display the addition of even numbers and product of odd numbers.

 

void main()

{

int a=0,m=1,i,num[5];

clrscr();

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

{

  printf(“\nEnter Number[%d]:”,i+1);

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

}

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

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

{

  if(num[i]%2==0)

  {

    printf(“\n Even Number : %d”,num[i]);

    a=a+num[i];

  }

  else

  {

    printf(“\n Odd Number : %d”,num[i]);

    m=m*num[i];

  }

}

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

printf(“\n Addition of Even Numbers : %d”,a);

printf(“\n Product of Odd Numbers :%d”,m);

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

}

OUTPUT:

Enter Number[1]: 1

Enter Number[2]: 2

Enter Number[3]: 3

Enter Number[4]: 4

Enter Number[5]: 5

================================

Odd Number : 1

Even Number : 2

Odd Number : 3

Even Number : 4

Odd Number : 5

=================================

Addition of Even Numbers : 6

Product of Odd Numbers : 15

=================================

Explanation:

In the above example, five integers are entered through the keyboard. To detect even and odd numbers mod(%) operation is carried out and remainder of each number is obtained. If the remainder is 0, then the number is even and added to variable ‘a’. If the remainder is non-zero then this number is multiplied to ‘m’. Variables ‘a’ and ‘m’ are initialized with 0 and 1, respectively. Both the variables are printed through printf() function which gives addition of even numbers and product of odd numbers, respectively.

7.8  Write and display a program to detect the occurrence of a character in a given string.

 

void main()

{

static char s[15];

int i,c=0;

char f;

clrscr();

puts(“Enter a String :”);

gets(s);

puts(“Enter a Character to Find :”);

f=getchar();

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

{

  if(s[i]==f)

  c++;

}

printf(“The Character (%c) in a String (%s) occurs %d times.”,f,s,c);

}

OUTPUT:

Enter a String : programmer

Enter a Character to Find : r

The Character (r) in a String (programmer) occurs (3) times.

Explanation:

In this program, the string and a single character are entered through the keyboard. Inside the for loop, the if statement checks each element of the string for the occurrence of the single entered character. If the character (‘r’) is found then ‘c’ counter is incremented otherwise without incrementing the counter loop continuous till ‘i’ reaches to 15. At last the value of ‘c’ gives the total occurrence of the given character.

7.9  Write a program to display the elements of two arrays in two separate columns and add their corresponding elements. Display the result of addition in the third column.

 

void main()

{

int i,num[]={24,34,12,44,56,17};

int num1[]={12,24,35,78,85,22};

clrscr();

printf(“Element of Array 1st − 2nd Array Addtion\n”);

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

{

  printf(“\n\t\t %d + %d = \t%d”,num[i],num1[i],num[i]+num1[i]);

}

}

OUTPUT:

Element of Array 1st − 2nd Array Addition

24 + 12 = 36

34 + 24 = 58

12 + 35 = 47

44 + 78 = 122

56 + 85 = 141

17 + 22 = 39

Explanation:

In the above program, two integer arrays are initialized and the corresponding elements of arrays are added through a simple arithmetic operation.

7.10  Write a program to enter a character and integer data type. Use the two-dimensional array. Perform and display the addition of three numbers.

 

Tips: The Unsigned character data type is capable of performing mathematical operations on numbers from 1 to 255.

 

void main()

{

static unsigned char l,r,i,real[3][5],ima[3][5];

long c;

clrscr();

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

{

  printf(“Enter Number[%d] :”,1+l);

  scanf(“%ld”,&c);

  r=c/255;

  i=c%255;

  real[l][5]=r;

  ima[l][5]=i;

}

c=0;

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

c=c+real[l][5]*255+ima[l][5];

printf(“\nSum of 3 Numbers :%3ld”,c);

getch();

}

OUTPUT:

Enter Number [1] : 5

Enter Number [2] : 4

Enter Number [3] : 3

Sum of 3 Numbers : 12

Explanation:

The unsigned character data type ranges from 0 to 255. In the above example, three numbers are entered. They are divided and the mod operation is carried out with 255. If the numbers are less than 255 neither division nor mod operations are carried out. Their sum is evaluated and displayed on the screen. In case the entered numbers are greater than 255, real and imaginary parts are computed and stored in the separate arrays. To obtain the whole number, the real part is multiplied with 255 and added to imaginary part.

7.11  Write a program to display names of days of a week using single-dimensional array having length of 7. (A week having seven days).

 

void main()

{

int day[7],i;

clrscr();

printf(“\nEnter numbers between 1 to 7 :\n”);

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

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

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

  switch(day[i])

  {

    case 1:

    printf(“\n%dst day of week is Sunday”,day[i]);

    break;

    case 2:

    printf(“\n%dnd day of week is Monday”,day[i]);

    break;

    case 3:

    printf(“\n%drd day of week is Tuesday”,day[i]);

    break;

    case 4:

    printf(“\n%dth day of week is Wednesday”,day[i]);

    break;

    case 5:

    printf(“\n%dth day of week is Thursday”,day[i]);

    break;

    case 6:

    printf(“\n%dth day of week is Friday”,day[i]);

    break;

    case 7:

    printf(“\n%dth day of week is Saturday”,day[i]);

    break;

    default :

    printf(“\n %dth is Invalid day”,day[i]);

  }

}

OUTPUT:

Enter numbers between 1 to 7 : 1 3 2 4 5 7 8

1st day of week is Sunday

3rd day of week is Tuesday

2nd day of week is Monday

4th day of week is Wednesday

5th day of week is Thursday

7th day of week is Saturday

8th is invalid day

Explanation:

In the above example, depending upon the value entered by the user, the switch() statement decides which day to print.

7.12  Write a program to display the contents of two arrays. The 1st array should contain the string and 2nd numerical numbers.

 

void main()

{

char city[6]={‘N’,’A’,’N’,’D’,’E’,’D’};

int i,pin[6]={4,3,1,6,0,3};

clrscr();

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

printf(“%c”,city[i]);

printf(“−”);

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

printf(“%d”,pin[i]);

}

OUTPUT:

NANDED – 431603

Explanation:

In the above example, two arrays of different data types are printed through printf() function. The two for loops are used for printing two arrays containing the first string and second numerics.

7.13  Write a program to display the number of days of different months of year.

 

# include <process.h>

void main()

{

int month[12]={31,28,31,30,31,30,31,31,30,31,30,31};

int i;

clrscr();

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

{

printf(“\n Month [%d] of a year contains %d days.”,i+1,month[i]);

printf(“\n”);

}

getche();

}

OUTPUT:

Month [1] of a year contains 31 days.

Month [2] of a year contains 28 days.

Month [3] of a year contains 31 days.

Month [4] of a year contains 30 days.

Month [5] of a year contains 31 days.

Month [6] of a year contains 30 days.

Month [7] of a year contains 31 days.

Month [8] of a year contains 31 days.

Month [9] of a year contains 30 days.

Month [10] of a year contains 31 days.

Month [11] of a year contains 30 days.

Month [12] of a year contains 31 days.

Explanation:

In the above example, one-dimensional array month[12] is initialized with the number of days of different months of a year from 1 to 12 as per their order. In prinf() function, number of days of the months are printed. The value of ‘i’ is incremented by one for obtaining the increasing order of the month of a year.

7.14  Write a program to display the number of days of a given month of a year.

 

# include <process.h>

void main()

{

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

int i,mn;

clrscr();

printf(“Enter Number of Month :”);

scanf(“%d”,&mn);

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

{

  if(mn==month[i])

  goto compare;

}

printf(“\n Invalid Month”);

exit(1);

compare:;

if(i+1==12)

printf(“Month (%d) Contains 28 days.”,month[i]);

if(i+1<8)

printf(“Month (%d) Contains 31 days.”,month[i]);

if(i+1>7 && i+1!=12)

printf(“Month (%d) Contains 30 days.”,month[i]);

getche();

}

OUTPUT:

Enter Number of Month : 2

Month (2) Contains 28 days.

Explanation:

This program is slightly different as compared to the last one. The numbers of days of different months of a year are sorted. For example, first seven (1,3,5,7,8,10,12) elements of an array have month numbers having 31 days, next four 30 days and last one 28 days. The user enters the month number and if statement checks where this month number appears in the array. Whenever there is a match control goes to the compare statements. The if statements print the number of days depending upon the conditions stated as above.

7.15  Write a program to find the average sales of an item out of 12 months sale.

 

void main()

{

float sum=0,avg=0;

int sale;

int item[12];

clrscr();

printf(“\tEnter Month No.-Sale of an Item/month\n”);

for(sale=0;sale<=11;sale++)

{

  printf(“\t\t %d =”,sale+1);

  scanf(“%d”,&item[sale]);

}

for(sale=0;sale<=11;sale++)

sum=sum+item[sale];

avg=sum/12;

printf(“\n\t Average Sale of an item /month=%f”,avg);

}

OUTPUT:

Enter Month No.−Sale of an Item/month

1 = 125

2 = 225

3 = 325

4 = 425

5 = 525

6 = 625

7 = 725

8 = 825

9 = 925

10 = 500

11 = 600

12 = 700

Average Sale of an item /month= 543.750000

Explanation:

In the above program, sales of 12 months are entered and stored in an array item[12]. By using the for loop the sum of sales of 12 months is calculated. Average of sales is then computed and the result is displayed.

7.16  Write a program to calculate and display the total cost of four models of Pentium PCs. Use the single-dimension arrays for PC codes, their price and quantity available.

 

void main()

{

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

long t=0,price[4]={25000,30000,35000,40000};

int stock[4]={25,20,15,20};

clrscr();

printf(“\t Stock & Total Cost Details \n”);

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

printf(“Model\t Qty.\tRate (Rs.) Total Value”);

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

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

{

printf(“\nPentium%d %d %8ld %15ld”,pccode[i],stock[i],price[i], price[i]*stock[i]);

t=t+price[i]*stock[i];

}

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

printf(“Total Value of All PCs in Rs. %ld”,t);

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

}

OUTPUT:

Stock & Total Cost Details

======================================

Model Qty.

Rate (Rs.)

Total Value

======================================

Pentium1 25

25000
625000

Pentium2 20

30000
600000

Pentium3 15

35000
525000

Pentium4 20

40000
800000

======================================

Total Value of All PCs in Rs.2550000

======================================

Explanation:

Here, in the above program, three integer arrays pccode[], price[] and stock[] are initialized. After this the for loop is used for finding the total value of the available stock of each model. The result is printed by using simple multiplication of price[] and stock[]. This product is then added to variable ‘t’, which is the total value. The for loop executes four times. At the end, variable ‘t’ gives us the total cost of all PCs. Total cost is printed with printf() statement.

7.17  Write a program to display the given message by using putc() and stdout() functions.

 

void main(void)

{

char msg[ ] = “C is Easy”;

int i = 0;

clrscr();

while(msg[i])

putc(msg[i++], stdout);

}

OUTPUT:

C is Easy

Explanation:

A character array and integer variable are initialized. Array always begins with element number 0. In case if ‘i’ is not initialized with 0 result provides garbage value. Standard stdout() function prints the string on console. Here, the string is ‘C is Easy’.

7.7  ONE-DIMENSIONAL ARRAY AND OPERATIONS

We learned how to declare, initialize and access the array elements. One-dimensional array elements may be shown in one row. So far, the examples, we discussed is of one-dimensional array.

Example:

int num[5]; // one dimensional array

One can perform numerous operations on elements of an array and the same are explained together with the following programs. We will learn how to traverse, insert, delete and display elements in the array during program execution.

Traversing: The operation of displaying or listing all elements of an array is called traversing. The following program explains traversing with one-dimensional array.

7.18  Write a program to read and display the elements of an array.

 

void main()

{

int num[5],j;

clrscr();

printf(“\n Enter five elements :”);

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

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

printf(“\n Elements Address”);

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

printf(“\n%d %u”,num[j],&num[j]);

getche();

}

OUTPUT:

Enter five elements: 4 6 4 2 1

Elements Address

4 65516

6 65518

4 65520

2 65522

1 65524

Explanation:

In the above program, an array num[] is declared. The first for loop with the help of scanf() statement reads the elements and places in the array. The element position is indicated by the loop variable j. Same procedure is applied for displaying elements. The printf() statement displays the elements and addresses on the screen.

From Figure 7.4, one can see that one-dimensional arrays are stored one after another in sequence in the memory.

In an array, we can insert, delete or add any element but we cannot insert or delete the memory location. We can change only values.

Figure 7.4  Array elements in memory

7.8  OPERATIONS WITH ARRAYS

Figure 7.5 shows frequently performed operations with arrays.

  1. Deletion
  2. Insertion
  3. Searching
  4. Merging
  5. Sorting

Figure 7.5  Operations with arrays

  1. Deletion: This operation involves deleting specified elements from an array. Now consider the following programs.

    7.19  Write a program to delete specified element from an array and rearrange the elements.

     

    void main()

    {

    int num[20]={0},j,k,n,p,t;

    clrscr();

    printf(“\n Enter number of elements :”);

    scanf(“%d”,&n);

    printf(“\n Enter elements :”);

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

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

    printf(“\n Elements are :”);

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

    printf(“\n %d %u”,num[j],&num[j]);

    printf(“\n Enter element number to delete :”);

    scanf(“%d”,&p);

    p−−;

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

    {

      if(j>=p)

      num[j]=num[j+1];

    }

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

    if(num[j]!=0)

    printf(“\n %d %u”,num[j], &num[j]);

    getche();

    }

    OUTPUT:

    Enter number of elements: 4

    Enter elements: 5 4 1 2

    Elements are:

    5 65482

    4 65484

    1 65486

    2 65488

    Enter element number to delete: 3

    5 65482

    4 65484

    2 65486

    Explanation:

    In the above program, an array num[20] is declared. The program asks for the number of elements to be entered. User has to enter the following input.

    1. Number of elements to be entered and integers.
    2. Element number to be erased from an array.

    The first for loop and scanf() statement reads numbers from keyboard and places in the array. In the second for loop onwards, the position of an element number is to be erased, the next array element is replaced with the previous one. Thus, the specified element is removed from an array. The third for loop and printf() statement display the elements of an array. You can see in the output that the third memory location is the same only if its contents are changed (see Figure 7.6 for view).

    Figure 7.6  Deletion in steps

  2. Insertion: This operation is used to insert an element at a specified position in an array. Consider the following program.

    7.20  Write a program to insert an element at a specified position in an array.

     

    void main()

    {

    int num[20]={0},j,k,n,p,t,s;

    clrscr();

    printf(“\n Enter number of elements :”);

    scanf(“%d”,&n);

    printf(“\n Enter elements :”);

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

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

    printf(“\n Elements and their locations are :”);

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

    printf(“\n%d %u”,num[j],&num[j]);

    printf(“\n Enter element and position to insert at :”);

    scanf(“%d %d”,&s,&p);

    p−−;

    for(j=n;j!=p;j−−)

    num[j]=num[j−1];

    num[j]=s;

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

    printf(“\n %d %u”,num[j],&num[j]);

    getche();

    }

    OUTPUT:

    Enter number of elements : 4

    Enter elements: 1

    2

    3

    4

    Elements and their locations are:

    1 65450

    2 65452

    3 65454

    4 65456

    Enter element and position to insert at: 9 2

    1 65450

    9 65452

    2 65454

    3 65456

    4 65458

    Explanation:

    This program is somewhat like previous program. Here, an element is inserted. The array elements are shifted to the next location and at a specified position and a space is created as shown in Figure 7.7 (b); the new element is inserted as shown in Figure 7.7 (c). Here, you can also see that though we inserted a new element, the memory location of the second element is the same (65452). Once again, it is proved that in array operation only contents of memory can change but the actual addresses remain as it is. The address of the first element, i.e. num[0] (65450), is called the base address. This address can also be stored in another pointer and array elements can be accessed. The next program is illustrated in this regard.

    1

    Figure 7.7  Insertion steps

    7.21  Write a program to display one-dimensional array using integer pointer.

     

    void main()

    {

    int *p,num[5]={4,5,6,7,8},j;

    clrscr();

    p=num;

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

    printf(“\n%d %u”,*(p+j),(p+j));

    getche();

    }

    OUTPUT:

    4 65486

    5 65488

    6 65490

    7 65492

    8 65494

    Explanation:

    In the above program, an integer array num[] is declared and initialized. In the same statement, pointer p and integer variable j are declared. The base address is assigned to pointer p. While assigning base address, it is enough to write the name of an array, and it is optional to write subscripts number, i.e. num[0][0]. The for loop executes five times and the value of j varies from 0 to 4. First time 0 is added to base address and there is no change in the address. Hence, 1st element is displayed. In the second iteration, one is added to the base address and it takes the next successive address and 2nd element is displayed. Same procedure is continued and array elements are displayed. Figure 7.8 simulates what exactly takes place.

    In the above figure, the first line of boxes contains values, second contains memory addresses and the third contains loop variable values as used in the last program. When the value of a loop variable is added to the base address, we get the successive memory address and values stored in them can be displayed.

    Figure 7.8  Accesses through base address

    In this example, the base address is 65486 and the address gets incremented by 2 due to integers.

    For example, at following locations the data observed is as follows:

     

    (65486)=4

     

    (65488)=5

     

    (65490)=6

     

    (65492)=7

     

    (65494)=8

     

  3. Searching: An array element can be searched. The process of seeking specific elements in an array is called searching.
  4. Merging: Merging of two arrays is an important operation with an array. The elements of two arrays are merged into a single one. The easier way of merging two arrays is first copy all elements of one array into third one and then copy all elements of the second array into the third one. We can also merge in alternate order as shown in the following program. Figure 7.9 indicates the merging of two arrays. One should take into account the following points:
    1. Elements of one array can be appended to end of the second array.
    2. Elements of two arrays can be merged in alternate order.
    3. The size of resulting array must be more than the size of the two arrays.

    7.22  Write a program to merge two arrays into third one. Display the contents of all the three arrays.

     

    void main()

    {

    int j,h=0,k=0;

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

    int y[4]={5,6,7,8};

    int z[8];

    clrscr();

    printf(“\n Array 1: −”);

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

    printf(“%d”,x[j]);

    printf(“\n Array 2: −”);

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

    printf(“%d”,y[j]);

    j=0;

    while(j<8)

    {

      if(j%2==0) z[j]=x[k++];

      else z[j]=y[h++];

      j++;

    }

    printf(“\n Array 3:”);

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

    printf(“%d”,z[j]);

    getche();

    }

    OUTPUT:

    Array 1:- 1 2 3 4

    Array 2:- 5 6 7 8

    Array 3: 1 5 2 6 3 7 4 8

    Explanation:

    In the above program, three integer arrays are declared and initialized. The first two for loops are used to view the elements of arrays X and Z by transverse process. The while loop is used to execute until the condition is true. The if() statement checks the condition and accordingly if and else blocks are executed. These statements also fetch element from both arrays placed into array 3 (see Figure 7.9).

    Figure 7.9  Merging two arrays

  5. Sorting: Arranging elements in a specific order either in ascending or in descending order is known sorting. Sorting is a very important operation and compulsorily used in database application programs. Let us study the following program, which sorts an array of integers, and store them in another array.

    7.23  Write a program to enter integer elements and sort them in ascending order.

     

    void main()

    {

    int num[5],j,k,s=0;

    clrscr();

    printf(“\n Enter five Elements :”);

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

    {

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

      s=s+num[j];

    }

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

    {

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

      {

        if(num[j]==k)

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

      }

    }

    }

    OUTPUT:

    Enter five Elements: 5 8 9 7 2

    2 5 7 8 9

    Explanation:

    In the above program, an integer array is declared and five numbers are entered. The sum of all the numbers is taken. Using nested loop, every number of an array is compared from one to s (s=sum of all numbers). The if statement checks every array element with the value of s and displays number in the ascending order. The sorting can be done in various ways. The above is the simplest way, but consumes more time for sorting.

7.9  PREDEFINED STREAMS

Following are the stream functions:

  1. stdin()
  2. stdout()
  3. stderr()

When C program is executed, a few ‘files’ are automatically opened by the system for use by the program. Constant FILE pointers recognize these files. Streams stdin, stdout and stderr are defined in the standard I/O include files. These are macros. Their details are illustrated in the chapter Preprocessor Directives.

  1. stdin:

    The file pointer stdin identifies the standard input text and it is associated with the terminal. All standard I/O functions perform input and do not take a FILE pointer as an argument and get their input from stdin.

  2. stdout: Similarly, it is used for outputting the text. It is a standard output stream.
  3. stderr: It is an output stream in the text mode. It is a standard error stream.

7.24  Write a program to read the text through keyboard and display it by using stdin and stdout streams.

 

void main(void)

{

char ch[11];

int i;

clrscr();

printf(“Input a Text:”);

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

ch[i]=getc(stdin);

printf(“The Text inputted was”);

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

putc(ch[i],stdout);

}

OUTPUT:

Input a Text: Hello World

The text inputted was Hello World

Explanation:

In the above program, two for loops are used. The first for loop reads input characters from the keyboard and stores in an array ch[11] by using stdin standard function. The second for loop displays the string using stdout standard function.

7.25  Write a program to sort the given strings alphabetically.

 

# include <ctype.h>

void main()

{

int i,j;

char text[30];

clrscr();

printf(“Enter Text Below :”);

gets(text);

clrscr();

printf(“Sorted Text Below :\n”);

for(i=65;i<=90;i++)

{

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

    {

        if( text[j]==toupper(i) || text[j]==tolower(i))

        printf(“%c”,text[j]);

    }

}

}

OUTPUT:

Enter Text Below :

Hello

Sorted Text Below :

Ehllo

Tips: The tolower and toupper are the ‘C’ functions for conversion from lower to upper or vice versa or convert numerical to its ASCII equivalent. For initializing these functions header file ctype.h is to be included

Explanation:

ASCII equivalents of alphabets are used to sort the given string. The standard functions toupper() and tolower() in the if statement are used to ignore the case; i.e. capitals or small letters are treated the same. If character value given by for loop ‘i’ and string text [] value denoted by for loop ‘j’ are the same that value gets printed, because the value of character supplied by the outer for loop is taken alphabetically. Hence, characters when matched get printed.

7.26  Write a program to arrange the numbers in increasing and decreasing order (ascending and descending order) using loops.

 

void main()

{

int i,j,sum=0,a[10];

clrscr();

printf(“Enter ten numbers :”);

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

{

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

  sum=sum+a[i];

}

printf(“Numbers In Ascending Order :”);

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

{

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

  {

    if(i==a[j])

    printf(“%3d”,a[j]);

  }

}

printf(“\nNumbers In Descending Order :”);

for(i=sum;i>=0;i−−)

{

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

  {

    if(i==a[j])

    printf(“%3d”,a[j]);

  }

}

}

OUTPUT:

Enter ten numbers : 5 2 1 4 7 9 10 12 9 3

Numbers In Ascending Order : 1 2 3 4 5 7 9 9 10 12

Numbers In Descending Order: 12 10 9 9 7 5 4 3 2 1

Explanation:

In the above program, 10 numbers are entered through the keyboard in an array a[10]. In the same loop, their sum is performed. The outer loop executes from 0 to variable ‘sum’. Here, ‘sum’ variable contains addition of all the 10 entered numbers. The inner loop checks all the values of an array a[10] with the current value of outer loop. The if statement checks the value of outer loop with the entire array, when it finds match number gets printed. The outer loop continues till it reaches the value of variable ‘sum’. The outer loop is in ascending order. So the elements of an array a[10] are printed in the ascending order. For descending order, the outer for loop is made descending.

 

OR

7.27  Write a program to sort the numbers in ascending order by comparison method.

 

void main()

{

int i,j,n,num[10],temp;

clrscr();

printf(“Enter how many numbers to sort :”);

scanf(“%d”,&n);

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

{

  printf(“Enter numbers # %2d:”,i+1);

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

}

printf(“The Numbers Entered through keyboard \n”);

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

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

for(i=0;i<n-1;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 The Numbers in ascending order \n”);

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

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

getch();

}

OUTPUT:

Enter how many numbers to sort : 5

Enter numbers # 1: 8

Enter numbers # 2: 3

Enter numbers # 3: 2

Enter numbers # 4: 1

Enter numbers # 5: 9

The Numbers Entered through keyboard

8 3 2 1 9

The Numbers in ascending order

1 2 3 8 9

Explanation:

Here, sorting of numbers is made through the exchange method. The element number given by the outer for loop of an array num [10] is compared with all the other elements of the same array. If the first element is larger than the successive element, the larger value is assigned to variable ‘temp’(temp=num[i];) and in place of larger value, smaller value is replaced (num [i]=num[j];). In place of smaller value, the value of ‘temp’ variable (which is larger) is replaced (num[j]=temp;). Thus, the array elements in ascending order are obtained using the above program.

7.28  Write a program to evaluate the following series. The series contains the sum of square of numbers from 1 to ‘n’. Store result of each term in an array. Calculate the value of ‘s’ using an array /* s= 12+22+32+42 ...n2 */.

 

# include <math.h>

void main()

{

static int sqr[15];

int i,n,s=0;

clrscr();

printf(“Enter value of n:”);

scanf(“%d”,&n);

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

sqr[i]=pow(i+1,2);

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

{

    printf(“%d\n”,sqr[i]);

    s=s+sqr[i];

}

printf(“Sum of square : %d”,s);

}

OUTPUT:

Enter value of n: 4

1

4

9

16

Sum of square : 30

Explanation:

The above program evaluates squares up to ‘n’ numbers. The value of ‘n’ is entered through the keyboard. Square of each number is stored in an array sqr[15] and their sum is calculated. Final result is displayed.

7.10  TWO-DIMENSIONAL ARRAY AND OPERATIONS

Two-dimensional arrays can be thought of rectangular display of elements with rows and columns. Consider the following example int x[3][3]; The two-dimensional array can be declared as in Figure 7.10.

Figure 7.10  Two-dimensional array

The arrangement of array elements shown in Figure 7.10 is only for the sake of understanding. Actually, the elements are stored in the contiguous memory locations. The two-dimensional array is a collection of two one-dimensional arrays. The meaning of the first argument is in x[3][3] means number of rows, i.e. the number of one-dimensional array and the second argument indicate the number of elements. The x[0][0] means the first element of the first row and column. In one row, the row number remains the same and the column number changes. The number of rows and columns is called the range of an array. A two-dimensional array clearly shows the difference between logical assumption and physical representation of the data. The computer memory is linear and any type of an array may be one, two or multi-dimensional, it is stored in the continuous memory location (Figure 7.11).

Figure 7.11  Storage of two-dimensional array

7.29  Write a program to demonstrate the use of two-dimensional array.

 

void main()

{

int i,j;

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

clrscr();

printf(“\n Array elements and address”);

printf(“\n\t Col-0 Col-1 Col-2”);

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

printf(“\nRow0”);

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

{

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

  printf(“%d [%u]”,a[i][j],&a[i][j]);

  printf(“\nRow%d”,i+1);

}

printf(“\r”);

}

OUTPUT:

Array elements and address

Explanation:

From the above program’s output, you can see that the memory address displayed is in sequence and it is true that the elements of two-dimensional array are stored in successive memory locations. The one-dimensional array can be accessed using a single loop. However, for two-dimensional array two loops are required for row and column. The inner loop helps to access the rowwise elements and outer loop changes the row number. Like, one-dimensional array base address of an array can be stored in pointer. Consider the following program:

7.30  Write a program to assign base address of two-dimensional array to pointer and display the elements.

 

#include<stdio.h>

#include<conio.h>

void main()

{

int *p,num[2][2]={4,5,6,7},j;

clrscr();

p=&num[0][0];

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

printf(“ %d %u\n”,*(p+j),unsigned(p+j));

getch();

}

OUTPUT:

4 65518

5 65520

6 65522

7 65524

Explanation:

The above program is the same as the last one. But the point to note here is that to store base address of two-dimensional array, it is not only enough to mention array, in addition subscript number and address operation also should be preceded. Then compiler accepts the statement; otherwise the compiler flags an error message. For one-dimensional array an array name is sufficient but onwards we have to mention element number with address operator.

7.10.1  Insert Operation with Two-Dimensional Array

We have studied the example of insertion of element with one-dimensional array. We are also aware of the fact how pointers can be used to access array elements. The following program gives you an idea of insert operation with two-dimensional array.

7.31  Write a program to illustrate insert operation with two-dimensional array.

 

void main()

{

int num[5][5]={0,0},j,*p,at,e,n;

clrscr();

printf(“\n Enter how many elements (<=25) :”);

scanf(“%d”,&n);

p=&num[0][0];

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

scanf(“%d”,p++);

p=&num[0][0]; printf (“\n”);

for(j=0;j<n;j++,p++)

printf(“%2d”,*p);

printf(“\n Enter a number & position to insert :”);

scanf(“%d %d”,&e,&at);

for(j=n;j>=at;j−−)

{

  *p=*(p−1);

  p−−;

}

*p=e;

p=&num[0][0];

for(j=0;j<=n;j++,p++)

printf(“%2d”,*p);

}

OUTPUT:

Enter how many elements (<=25): 5

1 2 3 4 5

1 2 3 4 5

Enter a number & position to insert: 8 3

1 2 8 3 4 5

Explanation:

In all types of array, one-, two- and three-dimensional elements are stored in successive memory locations. A pointer is used to get successive memory location of memory. In this way, elements of an array can be accessed, changed or replaced. For all this, we require only the base address of the array that is to be assigned to pointer.

Consider the statement p=&num [0][0]; used to store the base address (address of 0th element of the array) of an array. Later in the program, we need not access the array by its name and corresponding row, column numbers. The total capacity of array of storing element is 25 as per the declaration. The user is asked to enter the number of elements. The entered value is stored in variable n through the scanf() statement. Thus, using loops, values are repetitively entered and displayed.

The user is again asked to enter a number and position in the array where the element is to be inserted. These values are stored in variables (scanf (“%d %d”,&e,&at);) variables e and at.

 

for(j=n;j>=at;j−−)

{

*p=*(p−1);

p−−;

}

Using the for loop the elements are shifted to the next position up to the value of variable ‘at’.

When loop ends, the entered element is assigned to *(*p=e;). The ‘e’ element is already shifted to the next position. Thus, finally the list of the latest elements is displayed. Figures 7.12 (a) and (b) show the representation of the insertion of elements.

Figure 7.12  Insertion of element

7.10.2  Delete Operation with Two-Dimensional Array

Like insert operation delete operation can also be performed on an array. Consider the following program:

7.32  Write a program to demonstrate delete operation of element with two-dimensional array.

 

void main()

{

int num[5][5]={0,0},j,*p,at,e,n;

clrscr();

printf(“\n Enter how many elements (<=25) :”);

scanf(“%d”,&n);

p=&num[0][0];

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

scanf(“%d”,p++);

p=&num[0][0]; printf (“\n”);

for(j=0;j<n;j++,p++)

printf(“%d”,*p);

printf(“\n Enter Element number to delete :”);

scanf(“%d”,&at);

at−−;

p=&num[0][0];

p+=at;

for(j=at;j<n;j++)

{

  *p=*(p+1);

  p++;

}

*p=0;

p=&num[0][0];

while(*p!=0)

{

  printf(“%d”,*p);

  p++;

}

}

OUTPUT:

Enter how many elements (<=25) : 7

1 2 3 4 5 6 7

1 2 3 4 5 6 7

Enter Element number to delete: 5

1 2 3 4 6 7

Explanation:

The method obtaining base address and pointer arithmetic involved in the program is the same as the last program. The element to be deleted is replaced with the next element. Thus, the entire elements are shifted to previous location. Figures 7.13(a) and (b) describe the deletion of element.

Figure 7.13  Deletion of element

Two-dimensional array can be thought as a rectangular display of elements with rows and columns. For example, elements of int x[3][3] are shown in Table 7.5.

Table 7.5  Array elements in matrix form

The arrangement of array elements in Table 7.5 is only for the sake of understanding. Conceptually, the elements are shown in matrix form. Physically array elements are stored in one contiguous form in memory.

The two-dimensional array is a collection of a number of one-dimensional arrays, which are placed one after another. For example, in Table 7.5 each row of a two-dimensional array can be thought of as a single-dimensional array.

7.33  Write a program to display two-dimensional array elements together with their addresses.

 

void main()

{

int i,j;

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

clrscr();

printf(“Array Elements and addresses.\n\n”);

printf(“Col-0 Col-1 Col-2\n”);

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

printf(“row0”);

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

{

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

  printf(“%d [%5d]”, a[i][j], &a[i][j]);

  printf(“\nRow%d”,i+1);

}

printf(“\r”);

}

OUTPUT:

Explanation:

In the above program, two-dimensional array is declared and initialized. Using two nested for loops elements of array together with their addresses are displayed. It is shown at the output that elements of two-dimensional array are displayed in rectangle form. But, in memory they are not stored in this particular format. They are stored in contiguous memory location as shown in Table 7.6.

Table 7.6  Memory map of two-dimensional array elements

7.34  Write a program to display the balance and code number in two separate columns. Indicate the number of code, which are having the balance of less than 1000.

 

void main()

{

int bal[5][2],i,j=0;

clrscr();

printf(“\nEnter Code No & Balance:\n”);

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

scanf(“%d %d”,&bal[i][1],&bal[i][2]);

printf(“Your Entered Data :”);

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

{

  printf(“\n%d %d”,bal[i][1],bal[i][2]);

  if(bal[i][2]<1000)

  j++;

}

printf(“\nBalance Less than 1000 are %d”,j−1);

}

OUTPUT:

Enter Code No & Balance:

1 900
2 800
3 1200
4 550
5 600

Your Entered Data :

1 900

2 800

3 1200

4 550

5 600

Balance Less than 1000 are 4

Explanation:

The above program finds the number of balance deposits less than 1000. Through the keyboard the codeno and balance deposits are entered. The first for loop is initialized from 0 to less than five for inputting the codenos and their balance deposits. The second for loop is for displaying the entered elements. The if statement checks whether the balance deposit is less than 1000 or not. With this, the codenos having deposits less than 1000 are sorted out. The counter gets incremented when deposits are less than 1000.

7.35  Write a program to initialize single-and two-dimensional arrays. Accept three elements in single-dimension array. Using the elements of this array, compute addition, square and cube. Display the results in two-dimensional arrays.

 

void main()

{

  int i,j=0, a[3][3],b[3];

  clrscr();

  printf(“\n Enter Three Numbers :\n”);

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

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

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

  {

    a[i][j] = b[i]*2;

    a[i][j+1]=pow(b[i],2);

    a[i][j+2]=pow(b[i],3);

  }

  clrscr();

printf(“Number\tAddtion\t\t Square\t\t Cube\n”);

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

{

  printf(“\n%d”,b[i]);

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

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

  printf(“\n”);

}

getch();

}

OUTPUT:

Enter Three Numbers : 5 6 7

Explanation:

The one-dimensional array is used for storing the elements entered through the keyboard. The second for loop performs operations such as multiplication (double), square and cube. The square and cube of the entered numbers are performed by standard library function pow() defined in math.h. The results obtained are assigned to the corresponding elements of two-dimensional arrays. The elements of two arrays are displayed.

7.36  Read the matrix of the order up to 10 × 10 elements and display the same in the matrix form.

 

void main()

{

int i,j,row,col,a[10][10];

clrscr();

printf(“\n Enter Order of matrix up to (10 X 10) A :”);

scanf(“%d %d”,&row,&col);

printf(“\Enter Elements of matrix A :\n”);

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

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

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

printf(“\n The Matrix is: \n”);

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

{

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

  printf(“%6d”,a[i][j]);

  printf(“\n”);

}

}

OUTPUT:

Enter Order of matrix up to (10 X 10) A : 3 3

Enter Elements of matrix A :

3 5 8

4 8 5

8 5 4

The Matrix is :

3 5 8

4 8 5

8 5 4

Explanation:

In the above program, the order of the matrix is entered. The order of the matrix should be up to 10 × 10. For the sake of understanding, we have taken 3 × 3 matrix. Using the first two nested for loops with respect to rows and columns the elements of matrix are entered. The last two nested for loops are used for displaying the matrix elements with respect to row and column.

Transpose of the matrix: The transpose of matrix interchanges rows and columns, i.e. the row elements become column elements and vice versa.

7.37  Read the elements of the matrix of the order up to 10 × 10 and transpose its elements.

 

void main()

{

int i,j,row1,row2,col1,col2,a[10][10],b[10][10];

clrscr();

printf(“\n Enter Order of matrix up to (10 X 10) A :”);

scanf(“%d %d”,&row1,&col1);

printf(“\Enter Elements of matrix A :\n”);

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

{

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

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

}

row2=col1;

col2=row1;

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

{

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

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

}

printf(“\n The Matrix Transpose is \n”);

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

{

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

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

  printf(“\n”);

}

}

OUTPUT:

Enter Order of matrix up to (10 X 10) A : 3 3

Enter Elements of matrix A :

3 5 8

4 8 5

8 5 4

The Matrix is :

3 4 8

5 8 5

8 5 4

Explanation:

This program is the same as the last one. The difference between them is the first program displays the elements in the order in which they are entered. But in this program row and column elements are interchanged. This is obtained by interchanging the order of matrix through the statements row2=col1; & col2=row1;.

7.38  Write a program to perform addition and subtraction of two matrices whose orders are up to 10 × 10.

 

void main()

{

int i,j,r1,c1,a[10][10],b[10][10];

clrscr();

printf(“Enter Order of Matrix A & B up to 10 X 10:”);

scanf(“%d %d”, &r1,&c1);

printf(“Enter Elements of Matrix of A :\n”);

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

{

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

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

}

printf(“Enter Elements of Matrix of B :\n”);

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

{

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

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

}

printf(“\nMatrix Addition \n”);

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

{

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

  printf(“%5d”,a[i][j]+b[i][j]);

  printf(“\n”);

}

printf(“\nMatrix Subtraction \n”);

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

{

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

  printf(“%5d”,a[i][j]-b[i][j]);

  printf(“\n”);

}

getch();

}

OUTPUT:

Enter Order of Matrix A & B up to 10 X 10: 3 3

Enter Elements of Matrix of A :

4 5 8

2 9 8

2 9 4

Enter Elements of Matrix of B :

1 3 5

0 5 4

6 7 2

Matrix Addition

5 8 13

2 13 12

8 16 6

Matrix Subtraction

3 2 3

2 4 4

−4 2 2

Explanation:

The elements of two matrices are read in the same manner as described in the previous examples. Addition and subtraction are computed and the results are displayed. Addition of corresponding elements of A and B matrices is performed by the statement a[i][j]+b[i][j]. Similarly, for subtraction a[i][j]−b[i][j] statement is used.

7.39  Write a program to perform multiplication of two matrices whose orders are up to 10 × 10.

 

void main()

{

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

clrscr();

printf(“Enter Order of Matrix A & B up to 10 X 10:”);

scanf(“%d %d”, &r1,&c1);

printf (“Enter Elements of Matrix of A:\n”);

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

{

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

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

}

printf(“Enter Elements of Matrix of B :\n”);

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

{

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

  {

    scanf(“%d”,&b[i][j]);c[i][j]=0;

  }

}

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

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

  {

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

    {

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

    {

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

  }

}

}

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

{

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

printf(“%5d”,c[i][j]);

printf(“\n”);

}

getch();

}

OUTPUT:

Enter Order of Matrix A & B up to 10 X 10: 3 3

Enter Elements of Matrix of A :

4 5 8

2 9 8

2 9 4

Enter Elements of Matrix of B :

1 3 5

0 5 4

6 7 2

Matrix Multiplication

52  93 56

50 107 62

26  79 54

Explanation:

This program is the same as the last one. With the help of the first two for loops the elements of the first matrix are entered. In a similar way, by using the next two for loops, the elements of the second matrix are entered. The multiplication is performed in the last two for loops. In this program, multiplication of corresponding elements of two matrices are performed.

7.40  Write a program to read the quantity and price of various Pentium models using an array. Compute the total cost of all models.

 

void main()

{

int i;

long pc[4][2];

long t=0;

clrscr();

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

{

  printf(“\t Enter Qty. & Price for Pentium%d :”,i+1);

  scanf(“%ld %ld”,&pc[i][0],&pc[i][1]);

}

clrscr();

printf“=======================================\n”);

printf(“Model\t Qty.\tRate (Rs.) Total Value”);

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

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

{

  printf(“\nPentium%d %2ld %6ld %15ld”,i+1,pc[i][0],pc[i][1], pc[i][0]*pc[i][1]);

  t=t+pc[i][0]*pc[i][1];

}

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

printf(“Total Value of All PCs in Rs. %ld”,t);

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

}

OUTPUT:

Enter Qty. & Price for Pentium1 :25 25000

Enter Qty. & Price for Pentium2 :20 40000

Enter Qty. & Price for Pentium3 :15 35000

Enter Qty. & Price for Pentium4 :20 40000

Explanation:

Two-dimensional array is initialized for entering the quantity and price. The first for loop is used for entering the quantity and price of four models through keyboard. The second for loop is for computing total value of each model. This is obtained by multiplying price of each model with quantity. The product is added to variable ‘t’. At the beginning, the value of ‘t’ is 0. The equation t=t+pc[i][0]*pc[i][1] is executed four times for finding the total cost of all the models. The output displays model, quantity, price and total value of each model and the gross value.

7.41  Write a program to read the capacity of HD, its price and quantity available in the form of an array. Compute the cost of HD.

 

void main()

{

int i,j;

long hd[3][4],t=0;

clrscr();

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

{

  printf(“\t Enter Capacity,Price & Qty.:”);

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

  {

    scanf(“%ld”,&hd[i][j]);

  }

}

clrscr();

printf========================================\n”);

printf(“HD Capacity GB Price Rs.\tQuantity Total Value Rs.”);

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

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

{

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

  {

    printf(“%2ld”,hd[i][j]);

    printf(“\t\t”);

    if (i==2)

    {

      printf(“%5ld”,hd[i−1][j]*hd[i][j]);

      t=t+hd[i−1][j]*hd[i][j];

    }

  }

  printf(“\n”);

}

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

printf(“Total Value Rs. %37ld”,t);

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

}

OUTPUT:

Enter Capacity, Price & Qty.: 10 8000 25

Enter Capacity, Price & Qty.: 20 12000 20

Enter Capacity, Price & Qty.: 40 15000 15

Enter Capacity, Price & Qty.: 90 20000 10

Explanation:

In the above program, two-dimensional array hd[3][4] is initialized. The first two for loops are used for reading capacity, price and quantity of hard disk. The next two for loops are used for evaluating the product of quantity and price of hard disk. Here, the first row contains the capacity, the second row contains price and third row contains the quantity of hard disk. Here, first row does not require for computing purpose. To avoid this, the if statement is used. Total cost is obtained by using printf(“%5ld”,hd[i-1][j]*hd[i][j]) and t=t+hd[i-1][j]*hd[i][j] statements.

7.42  Write a program to display the names of the cities with their base addresses.

 

void main()

{

int i;

char city[5][8]={

“Mumbai”,

“Chennai”,

“Kolkata”,

“Pune”,

“Delhi” };

clrscr();

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

{

  printf(“Base Address = %u”,&city[i]);

  printf(“String = %s\n”,city[i]);

}

}

OUTPUT:

Base Address = 4028 String = Mumbai

Base Address = 4036 String = Chennai

Base Address = 4044 String = Kolkata

Base Address = 4052 String = Pune

Base Address = 4060 String = Delhi

Explanation:

In the above program, a two-dimensional character array[][] is initialized with city names. It prints the city name and base address using the ‘&’ operator. In all the base addresses, there is difference of eight locations because every string occupies 8 bytes. Though the string name occupies less than eight characters, the total space eight, which is allocated, is taken in account.

7.43  Write a program to display the binary bits corresponding to Hexadecimal numbers from 0 to F. Attach an odd parity to Hex numbers and display them.

 

void main()

{

int bin[16][4],x,y,a=0,c=0;

for(x=0;x<16;x++)

{

y=x;

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

  {

    bin[x][a]=y%2;

    y=y/2;

  }

}

clrscr();

printf(“\n Input Bits Parity Bits”);

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

for(x=0;x<16;x++)

{

c=0;

printf(“\n”);

  for(y=3;y>=0;y−−)

  {

    printf(“%3d”,bin[x][y]);

    if(bin[x][y]==1)

    c++;

  }

if (c%2==0)

printf(“%7d”,1);

else

printf(“%7d”,0);

}

}

OUTPUT:

Binary Bits

Parity Bits

=========

=========

0 0 0 0

1

0 0 0 1

0

0 0 1 0

0

0 0 1 1

1

0 1 0 0

0

0 1 0 1

1

0 1 1 0

1

0 1 1 1

0

1 0 0 0

0

1 0 0 1

1

1 0 1 0

1

1 0 1 1

0

1 1 0 0

1

1 1 0 1

0

1 1 1 0

0

1 1 1 1

1

Explanation:

In the above program, two for loops are used. The inner for loop generates four binary bits for each hexadecimal number and assigns it to array bin[][]. The 0 to F hexadecimal numbers are taken from the outer for loop. If the bit is 1 counter ‘c’ is incremented. The value of ‘c’ is checked for even or odd condition. If ‘c’ is odd the parity bit ‘0’ is displayed otherwise ‘1’. The output is displayed.

7.44  Write a program to convert binary to gray codes.

 

void main()

{

int bin[16][4],x,y,a=0,c=0;

clrscr();

for(x=0;x<16;x++)

{

  y=x;

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

  {

    bin[x][a]=y%2;

    y=y/2;

  }

}

clrscr();

printf(“\n Binary Bits Gray Bits”);

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

for(x=0;x<16;x++)

{

  printf(“\n”);

  for(y=3;y>=0;y–-)

  printf(“%3d”,bin[x][y]);

printf(“%5d %2d %2d %2d”,bin[x][3], bin[x][3]^bin[x][2],bin[x][2]^bin[x][1],bin[x][1]^bin[x][0]);

}

}

OUTPUT:

Binary Bits

Gray Bits

=========

=========

0 0 0 0

0 0 0 0

0 0 0 1

0 0 0 1

0 0 1 0

0 0 1 1

0 0 1 1

0 0 1 0

0 1 0 0

0 1 1 0

0 1 0 1

0 1 1 1

0 1 1 0

0 1 0 1

0 1 1 1

0 1 0 0

1 0 0 0

1 1 0 0

1 0 0 1

1 1 0 1

1 0 1 0

1 1 1 1

1 0 1 1

1 1 1 0

1 1 0 0

1 0 1 0

1 1 0 1

1 0 1 1

1 1 1 0

1 0 0 1

1 1 1 1

1 0 0 0

Explanation:

In this program, the binary bits corresponding to the Hex are obtained. The first two for loops accomplish this. Exclusive OR operation with previous and successive bits obtains the gray code. The MSB bits should not be changed.

7.11  THREE- OR MULTI-DIMENSIONAL ARRAYS

The C program allows array of two-or multi-dimensions. The compiler determines the restriction on it. The syntax of multi-dimensional array is follows:

 

data_type array_ name[size1][size2][size3]...[sizei];

where Si is the size of the ith dimensions.

Three-dimensional array can be initialized as follows:

 

int mat[3][3][3] =

{

1,2,3,
4,5,6,
7,8,9,
1,4,7,
2,5,8,
3,6,9,
1,4,4,
2,4,7,

8,8,5};

A three-dimensional array can be a thought of an array of arrays. The outer array contains three elements. The inner array size is two-dimensional with size[3][3].

7.45  Write a program to explain the working of three-dimensional array.

 

void main()

{

int array_3d[3][3][3];

int a,b,c;

clrscr();

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

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

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

array_3d[a][b][c]=a+b+c;

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

{

  printf(“\n”);

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

  {

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

    printf(“%3d”,array_3d[a][b][c]);

    printf(“\n”);

  }

}

}

OUTPUT:

0 1 2

1 2 3

2 3 4

1 2 3

2 3 4

3 4 5

2 3 4

3 4 5

4 5 6

Explanation:

The three-dimensional array array_3d is initialized. The first three for loops are used for adding the values of a, b and c. Here, initially a and b are zero and ‘c’ varies from 0 to 2. Hence, the addition of a, b and c will be 0 1 2. This will be printed in the first row. In the second output row in which a = 0 and b = 1, c varies from 0 to 2. Thus, the output of the second row will be 1 2 3. In this way, the values of a, b and c are changed and the total 27 iterations are carried out.

7.46  Write a program to explain the working of four-dimensional array.

 

void main()

{

int array_4d[2][2][2][2];

int a,b,c,d;

clrscr();

for(a=0;a<2;a++)

for(b=0;b<2;b++)

  for(c=0;c<2;c++)

    for(d=0;d<2;d++)

      array_4d[a][b][c][d]=a+b+c+d;

for(a=0;a<2;a++)

{

  printf(“\n”);

  for (b=0;b<2;b++)

  {

    for(c=0;c<2;c++)

    {

      for(d=0;d<2;d++)

      printf(“%3d”,array_4d[a][b][c][d]);

      printf(“\n”);

  }  }

}

}

OUTPUT:

0 1

1 2

1 2

2 3

1 2

2 3

2 3

3 4

Explanation:

Here, in the above-cited program, instead of three-dimension, four-dimension array is used. The operations performed are the same as explained in the previous example.

7.47  Write a program to read the quantity and rate of certain items using multi-dimensional array. Calculate the total cost by multiplying the quantity and rate and offer 2% discount on it and display the net amount.

 

void main()

{

long m[2][2][2][2];

int a,b,c,d;

clrscr();

printf(“Enter Quantity & Rate\n”);

for(a=0;a<2;a++)

  for(b=0;b<2;b++)

    for(c=0;c<2;c++)

      for(d=0;d<1;d++)

      {

        if(a==0)

        {

          printf(“a=%d b=%d c=%d d=%d\n”,a,b,c,d);

          scanf(“%ld %ld”,&m[a][b][c][d],&m[a][b][c][d+1]);

        }

        else

        {

          m[a][b][c][d]=m[a-1][b][c][d]*m[a-1][b][c][d+1];

          m[a][b][c][d+1]=m[a-1][b][c][d]*m[a-1][b][c] [d+1]*2/100;

        }

      } printf(“\t=====================================\n”); printf(“\tQuantity Rate Amount Discount (@2%) NetAmount\n”); printf(“\t=========================================\n”);

for(a=0;a<1;a++)

  for(b=0;b<2;b++)

    for(c=0;c<2;c++)

      for(d=0;d<1;d++)

      {

        printf(“\n%10ld %10ld”,m[a][b][c][d],m[a][b][c][d+1]);

        printf(“%8ld.00 %6ld.00 %12ld.00”, m[a+1][b][c] [d],m[a+1][b][c][d+1], m[a+1][b][c][d]-m[a+1][b][c][d+1]);

      } printf(“\n\t=======================================\n”); getch();

}

OUTPUT:

Enter Quantity & Rate

A=0 b=0 c=0 d=0

25 50

A=0 b=0 c=1 d=0

30 60

A=0 b=1 c=0 d=0

35 70

A=0 b=1 c=1 d=0

40 75

Explanation:

In the above example, the four-dimension array m[2][2][2][2] is declared. The first four for loops are used to read the quantity and rate. The values of variables ‘a’ and ‘d’ for four times remain zero whereas the values of ‘b’ and ‘c’ change to 1,(0,0), 2 (0,1), 3 (1,0) and 4 (1,1). This happens while execution of the for loops. The if statement checks as to whether the value of a = 0 or not. As long as its value is zero reading operation is performed. When it is greater than zero rate and quantity are multiplied for obtaining the amount. Also discount is calculated. Amount and discount are stored in the array m[2][2][2][2]. Net amount is printed after subtracting discount from the gross amount.

7.48  Write a program to demonstrate the use of three-dimensional array.

 

void main()

{

int a,b,c;

int mat[3][3][3] ={ 1,2,3,

4,5,6,
7,8,9,
1,4,7,
2,5,8,
3,6,9,
1,4,4,
2,4,7,
8,8,5 };

clrscr();

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

{ printf(“\n”);

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

  {

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

    printf(“%3d [%u]”,mat[a][b][c],&mat[a][b][c]);

    printf(“\n”);

} } }

OUTPUT:

1 [65470] 2 [65472] 3 [65474]

4 [65476] 5 [65478] 6 [65480]

7 [65482] 8 [65484] 9 [65486]

1 [65488] 4 [65490] 7 [65492]

2 [65494] 5 [65496] 8 [65498]

3 [65500] 6 [65502] 9 [65504]

1 [65506] 4 [65508] 4 [65510]

2 [65512] 4 [65514] 7 [65516]

8 [65518] 8 [65520] 5 [65522]

Explanation:

In the above example, a three-dimensional array is initialized. The three loops are used to access the elements. The logic of accessing elements is the same as two-dimensional array. From the output obtained, we can say that elements of multi-dimensional array are stored in continuous memory locations.

7.12  THE sscanf() AND sprintf() FUNCTIONS
  1. sscanf():

    The sscanf() function allows to read characters from a character array and writes them to another array.

    This function is similar to scanf() but instead from standard input it reads data from an array.

    7.49  Write a program to read string from a character array.

     

    void main()

    {

    char in[10],out[10];

    clrscr();

    gets(in);

    sscanf(in,“%s”,out);

    printf(“%s\n”,out);

    }

    OUTPUT:

    HELLO

    HELLO

    Explanation:

    In the above program, two character arrays in[10] and out[10] are declared. The gets() function reads the string through the terminal and it is stored in the array in[]. Till this time, the out[] array is empty. The sscanf() function reads characters from array in[] and assigns it to array out[]. Thus, both the arrays contain the same string. At the end, the printf() function displays the contents of array out[].

    7.50  Write a program to read integers in character array, convert and assigns them to integer variable using sscanf() function.

     

    void main()

    {

    int *x;

    char in[10];

    clrscr();

    printf(“\n Enter Integers :”);

    gets(in);

    sscanf(in,“%d”,x);

    printf(“\n Value of int x : %d”,*x);

    getche();

    }

    OUTPUT:

    Enter Integers : 123

    Value of int x : 123

    Explanation:

    In the above program, integer is read and stored in the character array in[]. The variable ‘x’ is declared as integer pointer. The sscanf() function assigns base address of array in[] to pointer ‘x’. The content of pointer ‘x’ is displayed using pointer notation ( * ).

  2. sprintf():

    The sprintf() function is similar to the prinf() function except a small difference between them. The printf() function sends the output to the screen whereas the sprintf() function writes the values of any data type to an array of characters. The following program is illustrated pertaining to sprintf().

    7.51  Write a program to explain the use of sprintf().

     

    void main()

    {

    int a=10;

    char c=‘C’;

    float p=3.14;

    char spf[20];

    clrscr();

    sprintf(spf,“%d %c %.2f”,a,c,p);

    printf(“\n%s”,spf);

    getche();

    }

    OUTPUT:

    10 C 3.14

    Explanation:

    In the above program, sprintf() stores the values of variables in the character array spf[]. When sprintf() function executes, the contents of variables are not be displayed on the screen. The contents of array spf is displayed using printf() function.

    7.52  Write a program to complete the string by filling the spaces with appropriate characters.

     

    void main()

    {

    char name[]=“Mas er ng A SI C”;

    int x=0;

    clrscr();

    printf(“Mastering ANSI C\n\n”);

    while(name[x]!=0)

    {

      if(name[x]==32)

      name[x]=getche();

      else

      putch(name[x]);

    x++;

    }

    getche();

    }

    OUTPUT:

    Mastering ANSI C

    Mastering ANSI C

    Explanation:

    In the above program, a string is initialized with array name []. The string is not complete and contains blanks. The if statement within the while() loop checks every character of the string. If blank space is found, if block is executed and user needs to enter a character. Otherwise, the next successive characters are displayed.

7.13  DRAWBACKS OF LINEAR ARRAYS
  1. The number of elements, which are to be stored in an array, is to be known first.
  2. When an array is declared, memory is allocated to it. If array is not filled completely, the vacant place occupies memory.
  3. Once the array is declared, its dimension can be changed.
SUMMARY

You have now learnt how to initialize an array by different ways. The Characteristics of an array have been discussed in depth. How to specify the elements of one-dimensional, two-dimensional and three-or multi-dimensional arrays is explained in detail together with ample examples. The functions such as the sscanf() and sprintf() functions are demonstrated through examples. In this chapter, the reader finds practical examples. The programmer should make an attempt to execute all the programs so as to get expertise in arrays. Unless the unsolved problems are taken up for solving, the depth of the chapter would not be followed.

EXERCISES

I  Fill in the blanks:

  1. In an array x[10], the x represents the______
    1. base address
    2. base value
    3. void pointers
  2. Each array element is stored in separate ________.
    1. memory locations
    2. value
    3. data type
  3. int x[5]; this array can hold values in between _______to__________.
    1. –32768 to 32767
    2. 0 to 255
    3. –32768 to 32768
  4. int x[5]={2,3,4,5,6}; the base address is 65564 then the location of element 2 is _____.
    1. 65564
    2. 65566
    3. 65568
  5. int x[3]= {1,2,3}; the address of x[2] is 65498, i.e. the base address of the array is _____
    1. 65494
    2. 65492
    3. 65496
  6. Output?

    void main()

    {

    int x[]={1,2.2,3},i;

    clrscr();

    printf(“%f”,x[1]);

    }

    1. the program will not run
    2. the program will run with warning messages
    3. None of the above
  7. The 1st element according to C compiler physically is a ______
    1. 2 nd element
    2. 0th element
    3. 1st element
  8. In long k[4] the total memory occupied by the array is ________.
    1. 16
    2. 8
    3. 4
  9. When in between two array of same type values are interchanged___________
    1. address of elements are also changed
    2. only base address of the array is changed
    3. None of the above happens
  10. int x[3] if x[0]=12 and x[2]=26 then x[3] is ______
    1. 0
    2. 15
    3. garbage value
  11. Array element counting starts from zero hence the statement x[0] defined can hold _____
    1. nothing
    2. one integer value
    3. one char value
  12. char c[]=“Hello” the H is stored at 65470 then the o is stored at _______
    1. 65474
    2. 65475
    3. 65480
  13. Array element of two dimensions are stored at _________.
    1. subsequent memory locations
    2. alternate memory locations
    3. any locations
  14. In________, values of the array elements are passed to function
    1. call by value
    2. call by reference
    3. None of them
  15. In________, addresses of the array elements are passed to function
    1. call by value
    2. call by reference
    3. None of them
  16. Fast access of array elements can be done using ________
    1. pointer
    2. call by value
    3. call by reference

II  True or false:

  1. When we declare array elements without initialization, then its elements are set to zero.
  2. If we declare static array without initialization, then its element are set to garbage value.
  3. When the size of an array is exceeded, then compiler will not show any error.
  4. It is not essential to mention the size of array while initializing it at the time of declaration.
  5. Speed of accessing array elements with pointers is slower than accessing by subscripts.
  6. Two-dimensional array is also called matrix.
  7. s[i][j] is two-dimensional array where -1 < i < 4 and -1 < j < 2 then we can say s[1][1] =*(*(s+1)+1).
  8. Array contains elements of the same data type which are stored contiguously in memory.
  9. Default storage class is static
  10. Storage class decides when to create and destroy variable.
  11. An integer array always terminates with ‘\0’ (null).
  12. When we assign one array to other, array elements of one are directly copied in to the other array.
  13. The output of the following program is ‘We won First Test against SriLanka’

     

    void main()

    {

    int num[]={24,34,12,44,57,9};

    int i = 0;

    if(num[i]=i[num])

      printf(“\n We won First Test against SriLanka”);

    else

      printf(“\n We won Second Test against SriLanka”);

    getch();

    }

  14. Output of the following program is 4

     

    void main()

    {

    int arr[]={10,20,30,45,67,56,74};

    int *i,*j;

    i=&arr[1];

    j=&arr[5];

    printf(“%d”,j-i);

    getch();

    }

  15. Output of the following program is 67

     

    void main()

    {

    int arr[]={10,20,30,45,67,56,74};

    int *j;

    clrscr();

    j=&arr[5];

    printf(“%d”,*(j-1));

    getch();

    }

  16. Character array never ends with ‘\0’(NULL).

III  Select the appropriate option from the multiple choices given below:

  1. An array is a collection of
    1. elements of different data types
    2. same data types
    3. Both A and B
  2. Array elements are stored in
    1. scattered memory locations
    2. sequential memory locations
    3. Both (a) and (b)
  3. A character array always ends with
    1. null (‘\0’) character
    2. question Mark (?)
    3. full Stop (.)
  4. If you declare array without static the elements will be set to
    1. null value
    2. zero
    3. garbage value
  5. Arrays cannot be initialized if they are
    1. automatic
    2. external
    3. static
    4. None of the above
  6. All the elements in the array must be
    1. initialized
    2. defined
    3. Both (a) and (b)
    4. None of the above
  7. What will be the output of the following program

     

    void main()

    {

    int a1[5]={1};

    int b=0,k=0;

    clrscr();

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

    {

      printf(“%3d”,++a1[0]);

    }

    }

    1. 2 3 4 5 6
    2. 1 2 3 4 5
    3. 1 1 1 1 1 1
    4. 1 2 2 2 2 2
  8. What will be the value of *x?

     

    void main()

    {

    int *x;

    char in[10]=“10”;

    clrscr();

    sscanf(in,“%d”,x);

    printf(“\n Value of int x : %d”,*x);

    }

    1. 10
    2. 012
    3. “1”
  9. What will be the output of the following program?

     

    void main()

    {

    int j[]={5,1,2,5,4,8};

    int m[]={1,5,8,4,5,9};

    int l[]={1,2,9,1,5,9},k;

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

    l[k]=j[k]+m[k]-l[k];

    clrscr();

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

    printf(“%d”, l[k]);

    }

    1. 5 4 1 8 4 8
    2. 5 5 1 8 4 9
    3. 1 2 5 5 5 9
  10. What is the output of the following program?

     

    void main()

    {

    int j[]={15,11,17,15,14,18};

    int m[]={1,5,8,4,5,9};

    int l[]={1,2,9,1,5,9},k;

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

    l[k]=j[k]-m[k]/l[k];

    clrscr();

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

    printf (“%d”, l[k]);

    }

    1. 14 9 17 11 13 17
    2. 12 8 16 10 12 16
    3. 14 19 17 10 12 11
  11. What is the output of the following program?

     

    void main()

    {

    char a[]={‘A’,‘B’,‘C’,‘D’,‘E’,‘F’};

    char b[]={‘0’,‘1’,‘2’,‘3’,‘4’,‘4’};

    char c[6],k;

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

    c[k]=a[k]+b[k];

    clrscr();

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

    printf(“%c”, c[k]);

    }

    1. q s u w y z
    2. Q S U W Y Z
    3. K J L M N O
  12. What will happen if you enter (at run time) more values into an array than its capacity?
    1. program will be terminated
    2. run time error message will be displayed
    3. No bug
  13. What will happen if you assign values in few locations of an array?
    1. rest of the elements will be set to 0
    2. compiler error message will be displayed
    3. possible system will crash
  14. When an array is passed to function, in real what gets passed?
    1. base address of the array
    2. element numbers
    3. values of the array
  15. Which is the correct statement to declare an array?
    1. int x[];
    2. int x[5];
    3. int x{5}’
  16. The array name itself is pointer to
    1. 0th element
    2. 1st element
    3. last element
  17. The array name itself is a
    1. constant pointer object
    2. address
    3. None of the above
  18. int x[5],*p; and p=x; then following which one operation is wrong ?
    1. x++;
    2. p++;
    3. p=x[1];
  19. int x[3]; the base address of x is 65460 the elements are stored at locations
    1. 65460, 65462, 65464
    2. 65460, 65461, 65462
    3. 65460, 65464, 65468
  20. int j[4] the sizeof(j) and sizeof(int) will display the value
    1. 8,2
    2. 2,8
    3. 2,2

IV  Attempt the following programming exercises:

  1. Write a program to read 10 integers in an array. Find the largest and smallest number.
  2. Write a program to read a number containing five digits. Perform square of each digit. For example, number is 45252. Output should be square of each digit, i.e. 4 25 4 25 16.
  3. Write a program to read a number of any lengths. Perform the addition and subtraction on the largest and smallest digits of it.
  4. Write a program to read three digits positive integer number ‘n’ and generate possible permutation of numbers using their digits. For example, n=123 then the permutations are 123, 132, 213, 231,312,3218.
  5. Write a program to read the text. Find out number of lines in it.
  6. Write a program to read any three characters. Find out all the possible combinations.
  7. Write a program to enter string in lower and uppercase. Convert lower to uppercase and vice versa and display the string.
  8. Read the marks of five subjects obtained by five students in an examination. Display the top two student codes and their marks.
  9. Write a program to enter five numbers using array and rearrange the array in the reverse order. For Example numbers entered are 5 8 3 2 4 and after arranging array elements must be 4 2 3 8 5.
  10. Accept a text up to 50 words and perform the following actions.
    1. Count total vowels, consonants, spaces, sentences and words with spaces
    2. Program should erase more than one space between two successive words.

      Hint: total number of sentences can be computed based on total number of full stops.

  11. Evaluate the following series. Calculate every term and store its result in an array. Using array calculate the final result.
    1. x= 11+22+33+44nh
    2. x=1! + 2! + 3!+ … n!
    3. x=1!-2!+3!- . . . . n!
  12. Refer the given below tables. Write a program to calculate bill amount of stationary articles. Use array for initializing items and their prices.
    1. Item

      Price ()

      10th Book Set

      850

      12th Book Set

      1150

      Note books

      Rate (Rs.)

      100 Pages/dozen

      75

      200 pages/dozen

      125

      PEN SET

      50

    2. 15% discount if sets are more than 10 otherwise 10%.
    3. 10% discount if notebooks are more than 10 dozen.
  13. Consider the following table and write a program to find the total cost of the computer systems using arrays. 10% discount is to be offered in case the total systems sold are more than 5 in quantity. Display the code, parts of the system and price. User should enter the configuration and quantity.

    Code No.

    Particulars

    Price ()

    1

    MOTHER BOARD WITH PROCESSOR P3 600 MHz

    3000

    2

    MOTHER BOARD WITH PROCESSOR P4 1000 MHz

    8000

    3

    HD (200 GB)

    4000

    4

    HD (400 GB)

    8000

    5

    RAM (1 GB)

    1000

    6

    RAM (2 GB)

    2000

    7

    CACHE (256 MB)

    1000

    8

    CACHE (1 GB)

    1500

    9

    FDD (1.44 MB)

    1500

    10

    CD ROM DRIVE

    3000

    11

    CABINET

    400

    12

    KEYBOARD

    750

    13

    MOUSE

    200

    14

    MULTIMEDIA KIT

    3000

    15

    MODEM

    1500

  14. Enter the following information through the keyboard using multi-dimension arrays. Calculate the salary of individuals and total salary of all employees.
  15. Refer the table given below. Find the total bill amount using arrays. The user should have option to enter the quantity of bulbs.

    Code No.

    Wattage of  the bulb

    Price/bulb ( )

    1

    15 W

     5

    2

    40 W

    8

    3

    60 W

    12

    4

    100 W

    20

    5

    200 W

    35

  16. Write a program to display the different parameters of 10 men in a table. The different parameters to be entered are height, weight, age and chest in cm. Find the number of men who satisfy the following condition.
    1. Age should be greater than 18 and less than 25.
    2. Height should be between 5.2 to 5.6 inches.
    3. Weight should be in between 45 to 60 kg.
    4. Chest should be greater than 45 cm.
  17. Write a program to display the items that have been exported between 1995 and 2000. The table should be displayed as follows. Input the amount of various items described as under.
    1. Find the total and average export value of all the items.
    2. Find the year in which minimum and maximum export was made.

      Items/Year 1995–96 1996–97 1997–98 1998–99 1999–2000

      Coffee

      Tea

      Sugar

      Milk powder

      Zinger

  18. Write a program to replace the zero with successive number in following arrays.
    1. int x[8] ={1,0,3,0,5,0,7,0}
    2. int y[8] = {-1,0,-3,0,-5,0,-7,0}

V  Answer the following questions:

  1. Explain multi-dimensional array.
  2. Array name contains base address of the array. Can we change the base address of the array?
  3. What is the relation between array name and element number? How elements are referred using base address.
  4. Can we store values and addresses in the same array? Explain.
  5. Mention differences between character array and integer array.
  6. What are arrays?
  7. How elements of an array are stored?
  8. Explain two-dimensional array.
  9. What are the drawback of liner array?
  10. Explain insertion and deletion of an array.
  11. Explain various operations with an array.

VI  What will be the output/s of the following program/s?

  1. void main()

    {

    int i,marks[5]={55,56,67,78,64};

    clrscr();

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

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

    getche();

    }

  2. void main()

    {

    char name []={’a’,’m’,’i’,’t’};

    int i;

    clrscr();

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

    printf(“%c”,name[i]);

    getche();

    }

  3. Sum of numbers from 1 to 10

    void main()

    {

    int i,sum=0,num[]={1,2,3,4,5,6,7,8,9,10};

    clrscr();

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

    sum=sum+num[i];

    printf(“%d”,sum);

    getche();

    }

  4. A program on multiplication table of 6

    void main()

    {

    int i,ans,num[5]={1,2,3,4,5};

    clrscr();

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

    {

      ans=num[i]*6;

      printf(“\n   %d*%d=%d”,6, num[i],ans);

    }

    }

  5. Factorial of 5

    void main()

    {

    int i,m=1,num[5]={1,2,3,4,5};

    clrscr();

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

    m=m*num[i];

    printf(“Total is %d”,m);

    getche();

    }

  6. Searching an element in the array.

    void main ()

    {

    int n=9,i;

    int x[5]={2,3,4,6,7};

    clrscr();

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

    printf(“ %d”,x[i]);

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

    {

      if(x[i]==n)

      {

        printf(“\n Element %d found in the array”,n);

        getche();

        exit();

      }

    }

    printf(“\n Element %d not found in the array”,n);

    getche();

    }

  7. Sum of even and odd numbers from

    void main()

    {

    int sumo=0,sume=0,i=0,odd[5],even[5];

    clrscr();

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

    {

      if i%2==0)

      sume=i+sume;

      else

      sumo=i+sumo;

    }

    printf(“Addition of even and odd numbers from 1 to 10 : %d %d”, sume,sumo);

    getche();

    }

VII  Find the bugs in the following program/s:

  1. void main()

    {

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

    int i,result=1;

    clrscr();

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

      result=result*a[i];

      printf(“\nresult of multiplication =%d”,result);

       getche();

    }

  2. void main()

    {

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

    int i,sum=0;

    float avg;

    clrscr();

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

    {

      sum=sum+a[i];

    }

    avg=(float)sum/10;

    printf(“\nSum of ten numbers =%d”,&sum);

    printf(“\nAverage of ten numbers=%.2f”,&avg);

    getche();

    }

  3. void main()

    {

    int i,num[]={24,34,12,44,56,17};

    int num1[]={12,24,35,78, 85,22};

    clrscr();

    printf(“Array 1st − 2nd Array Addtion\n”);

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

    {

    num[i]=num1[i]+ ++num[i];

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

    }

    }

  4. void main()

    {

    int i,num[]={24,34,12,44,56,17};

    clrscr();

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

    {

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

    }

    }

  5. void main()

    {

    int i,j;

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

    clrscr();

    clrscr();

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

    printf (“%u”,*(k+j));

    }

ANSWERS

I  Fill in the blanks:

Q.
Ans.

1.

a

2.

a

3.

a

4.

a

5.

a

6.

a

7.

b

8.

a

9.

c

10.

a

11.

a

12.

a

13.

a

14.

a

15.

b

16.

a

II  True or false :

Q.
Ans.

1.

False. Default declaration is auto, where elements are initialized to garbage value.

2.

False. They are set to zero.

3.

True. It is not compiler’s job to check whether array size is exceeded or not. So no error will be shown by the compiler.

4.

True. E.g.: int n[ ]={2,4,12,34}; is accepted.

5.

False. Speed of accessing array elements by pointer is always faster.

6.

True.

7.

True. Let us take an example:

 

void main()

 

{

 

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

 

int a = *(*(arr + 1) + 1);

 

int b = arr[2][1];

 

clrscr();

 

printf(“a = %d \t b = %d” a, b);

 

}

 

OUTPUT:

 

a = 4 b = 6

8.

True.

9.

False. Default storage class is auto.

10.

True.

11.

False. Character array always ends with ‘\0’.

12.

False. C doesn’t allow it. We’ve to copy content of one array element by element to other array.

13.

True.

14.

True.

Because, Suppose address start from 0

address of arr[1] = 2 address of arr[5] = 10

ans = (10−2)/2

In windows int has 2 byte size. So divide by 2.

15.

True

Access of any array element is possible with pointer

16.

False

III  Select the appropriate option from the multiple choices given below:

Q.
Ans.

1.

b

2.

b

3.

a

4.

c

5.

d

6.

d

7.

a

8.

a

9.

a

10.

a

11.

a

12.

c

13.

a

14.

a

15.

b

16.

a

17

b

18.

c

19.

a

20.

a

VI  What will be the output/s of the following program/s?

Q.
Ans.

1.

67

78

64

2.

a m i t

3.

55

4.

6*1=6

6*2=12

6*3=18

6*4=24

6*5=30

5.

Total is 120

6.

2 3 4 6 7

7.

Element 9 not found in the array

Addition of even and odd numbers from 1 to 10 : 24 21

VII  Find the bugs in the following program/s:

Q.
Ans.

1.

No bug. The for loop should be from 0 to 4 instead up to 5.

2.

& should be removed from the printf statements.

Ans Sum 57 and average 5.7

3.

No bug.

4.

No bug.

5.

Attempt to read more elements than declared in array. Last value of array displayed will be garbage.