2 Data Structures: Array – Introduction to Data Structures in C

Chapter 2

Data Structures: Array

Chapter Outline

2.1 INTRODUCTION

Array means collection. An array is used to store elements of the same type. It is a very popular and useful data structure and stores data elements in contiguous locations. More than one element is arranged in sequence so it is also called a composite data structure. Array is a linear and homogenous data structure. Homogenous means that the same types of elements are stored in it. It can be combined with a non-homogenous structure and a complex data structure can be created. We know that an array of structure objects can also be useful. Array of any standard or custom data type can be declared. The array of character (strings) type works somewhat differently from the array of int, float, etc.

When we declare a variable for example,

int x;

The variable x is declared and a memory location of two bytes is allocated to it. Later, a single value can be stored in it as shown in Fig. 2.1.

x=4;

Figure 2.1 Variable, value and address

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

2.1.1 Array Declaration and Initialization

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

a) int num[5];

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

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

In the above statement, all elements are initialized. It is also possible to initialize individual elements as follows:

num[0]=1;

num[1]=2;

num[2]=4;

num[3]=2;

num[4]=5;

The initialization can be done at compile time or dynamically at run time. The above is an example of compile-time initialization. In the statement (b) declaration and initialization is done at once. In such declaration, the number of elements (5) need not be mentioned in the []. The compiler automatically counts the values 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 upper element. In 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 the constant pointer and, therefore, we cannot modify it. Storing elements in successive 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 the address of the memory location where element 1 is stored as shown in Fig. 2.2. The address stored in the array name is called the base address. To access individual elements, the following syntax is used:

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

Figure 2.2 Arrays of integers

An array is a collection of elements of the same data type, stored in unique and contiguous memory locations.

2.1.2 Array Terminology

Size The number of elements or the array’s capacity to store elements denotes the size, which is always mentioned in the bracket ([]).

Type Types refers 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) element is a base address. The array name itself stores the address of the first element.

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

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

Word This indicates the space required for an element. In each memory location, a computer can store a data piece. The space occupied varies from machine to machine. If the size of the element is more than word (one byte) then it occupies two successive memory locations. The various data types such as integer, float, long, etc. needs more than one byte in memory.

2.2 CHARACTERSTICS OF ARRAYS
  1. Array elements are stored in successive memory locations.

    Example 2.1

    Write a program to display array elements with their addresses.

    Solution

    # include <stdio.h>

    # include <conio.h>

    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]);

    }

    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. The memory locations displayed have a difference of two. From the above program, it is clear that array elements are stored in successive memory locations. Fig. 2.3 shows the memory location and the values stored.

    Figure 2.3 Storage of one-dimensional array

  2. Once the array is declared, its lowest bound cannot be changed, but the upper bound can be expanded with the C++ compiler. The array name itself is a constant pointer and we cannot modify it. Therefore, the lowest bound of an array cannot be expanded.

    Example 2.2

    Write a program to demonstrate that the upper bound of an array can be expanded.

    Solution

    # include <stdio.h>

    # include <conio.h>

    main ()

    {

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

    Num[5]=6;

    clrscr();

    printf ("Num[5]=%d",Num[5]);

    }

    OUTPUT

    Num[5]=6

    Explanation In this program array, Num [5] is declared with the array size 5 and it is initialized with five elements. In the next statement, the 6th element is also initialized and displayed. Hence, we can say that the upper bound of an array can be expanded. If you try this program with a C compiler, a run time error message will be displayed.

  3. We know that the array name itself is a pointer. Though it is a pointer, it does not need the ‘*’ operator. The brackets [] automatically denote that the variable is a pointer.
  4. All the elements of an array share the same name, and they are distinguished from one another with the help of the element number.
  5. The amount of memory required for an array depends upon the data type and the number of elements.

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

  6. Operations such as insertion and deletion of element done with a list cannot be done with an array. Once an array is created, we cannot remove or insert memory locations. An element can be deleted or replaced but the memory location remains as it is.
  7. When an array is declared and not initialized, it contains garbage values. If we declare 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 the program executes. To overcome this problem, we initialize the first element of an array with zero or any other number. All the remaining elements are automatically initialized to zero, provided that the initialization is done in the declaration statement of array. The following program illustrates this:

    Example 2.3

    Write a program to initialize an array.

    Solution

    # include <stdio.h>

    # include <conio.h>

    main ()

    {

    int Num[5]={0}j;

    clrscr();

    printf("The elements in array after initialization ");

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

    printf ("\nNum[%d]=%d"j,Num[j]);

    }

    OUTPUT

    The elements in an array after initialization

    Num[0]=0

    Num[1]=0

    Num[2]=0

    Num[3]=0

    Num[4]=0

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

2.3 ONE-DIMENSIONAL ARRAYS

We have learnt how to declare, initialize and access the array elements. A one-dimensional array does not have any corresponding elements; it has only one row of elements. So far, the example we have discussed is of a one-dimensional array.

For example,

int Num[5]; // one dimensional array

In the following program we learn how to store and display values 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 a one-dimensional array:

Example 2.4

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

Solution

# include <stdio.h>

# include <conio.h>

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%3d %10u ",num[j],&num[j]);

}

OUTPUT

Enter five elements: 4 6 4 2 1

 

Elements

Address

4

65516

6

65518

4

65520

2

65522

1

65524

Explanation In this 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. The same procedure is applied for displaying elements. The printf () statement displays the elements and addresses on the screen. The %3d and the %10u is used to display the space.

From Example 2.4 we can see that elements in a one-dimensional array are stored one after another in sequence in memory. In the array we can insert, delete, or add any element but we cannot insert or delete the memory location. We can change only the values.

2.4 OPERATION WITH ARRAYS

Fig. 2.4 shows operations frequently carried out with arrays.

Figure 2.4 Elements in memory

Figure 2.5 Operations with arrays

2.4.1 Deletion

This operation involves deleting specified elements from the array. Now, consider the following programs:

Example 2.5

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

Solution

# include <stdio.h>

# include <conio.h>

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 Num[j]=%d",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 ("\nNum[j] = %d",Num[j]);

}

OUTPUT

Enter Number of elements: 5

Enter elements: 9 4 6 3 2

Elements are:

Num[j]=9

Num[j]=4

Num[j]=6

Num[j]=3

Num[j]=2

Enter element number to delete: 5

Num[j] = 9

Num[j] = 4

Num[j] = 6

Num[j] = 3

Explanation In this program, an array Num [20] is declared. The program asks for number of elements to be entered. The 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.

In the first for loop scanf statement reads the numbers from the keyboard and places it in the array. In the second for loop the array elements are displayed. After this for loop the number to be deleted is entered through the keyboard. In the third for loop the entered element is compared with all array elements. When match is found, the element is deleted and successive elements are pushed in their previous memory locations. The fourth for loop and printf statement display the elements of the array. You can see in the output that the third memory location is the same; only its contents are changed. See Fig. 2.6.

Figure 2.6 Deletion in steps

2.4.2 Insertion

This operation is used to insert an element at specified positions in an array. Consider the following program.

Example 2.6

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

Solution

# include <stdio.h>

# include <conio.h>

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 are: ");

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

printf ("\n num[j]: %d",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 num[j] = %d",num[j]);

}

OUTPUT

Enter number of elements: 5

Enter elements: 1 2 3 4 5

Elements are:

num[j]: 1

num[j]: 2

num[j]: 3

num[j]: 4

num[j]: 5

Enter element and position to insert at: 2 5

num[j] = 1

num[j] = 2

num[j] = 3

num[j] = 4

num[j] = 2

num[j] = 5

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

Figure 2.7 Insertion steps

Example 2.7

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

Solution

# include <stdio.h>

# include <conio.h>

int main ()

{

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

clrscr();

p=num;

printf("Elements Address");

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

printf ("\n %3d %7u", *(p+j),(p+j));

}

OUTPUT

 

Elements

Address

4

65516

5

65518

6

65520

7

65522

8

65524

Explanation In this 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 the base address it is enough to write the name of the array. It is optional to write subscript number, i.e. num [0][0]. The for loop executes five times and the value of j varies from 0 to 4. The first time 0 is added to the base address and there is no change in the address. Hence, the 1st element is displayed. In the second iteration, one is added to the base address. It takes the next successive address and the 2nd element is displayed. The same procedure is continued and array elements are displayed. Fig. 2.8 shows what exactly takes place.

Figure 2.8 Accesses through base address

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

For example,

65516+0 = 65516, i.e. 4

65516+1= 65518, i.e. 5

and so on values can be retrieved.

2.4.3 Searching

The process of seeking specified elements in an array is called searching.

Example 2.8

Write a program to search for a specified element in an array.

Solution

# include <stdio.h>

# include <conio.h>

main ()

{

int j=0,n;

int x[10];

clrscr();

printf("Enter ten elements of array:\n");

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

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

printf ("\n Enter element to search:");

scanf ("%d",&n);

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

{

      if (x[j]==n)

      break;

}

if(x[j]==n)

printf("\n Element found");

else

printf("Element is not found");

}

OUTPUT

Enter ten elements of array:

1 2 3 4 5 6 7 8 9 12

Enter element to search: 3

Element found

Explanation In the above program, an integer array is declared and initialized with elements. The element which is to be searched is entered through the keyboard. Using while loop, all the elements are read. The if statement checks every element with the array elements. When the if condition is satisfied the, message "element found" is displayed. Thus, the specified element can be searched. When the element is not found the message displayed will be "Element is not found".

2.4.4 Merging

The merging of two arrays into a single one is an important operation. The easiest way of merging two arrays is first, to copy all elements of one array into a third one and then copy all elements of the second array also into the third one. We can also merge elements in an alternate order as shown in the following program. Figure 2.9 indicates the merging of two arrays. The following points should be taken into account.

  1. Elements of one array can be appended to the end of the second array.
  2. Elements of two arrays can be merged in an alternate order.
  3. The size of the resulting array must be more than the size of two arrays.

Example 2.9

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

Solution

# include <stdio.h>

# include <conio.h>

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 X: ");

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

printf (" %d ",x[j]);

printf ("\n Array Y: ");

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 Z: ");

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

printf (" %d ",z[j]);

}

OUTPUT

Array X: 1 2 3 4

Array Y: 5 6 7 8

Array Z: 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 array x and z by a 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 elements from both arrays and place them into array z. Fig. 2.9 illustrates the merging of two arrays.

Figure 2.9 Merging two arrays

2.4.5 Sorting

Arranging elements in a specific order, either ascending or descending, is known as 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 stores them in another array.

Example 2.10

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

# include <stdio.h>

# include <conio.h>

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 loops every number of the 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 the numbers in ascending order. Sorting can be done in various ways. The above sorting method is the simplest one.

2.5 TWO-DIMENSIONAL ARRAYS

Two-dimensional arrays can be thought of as rectangular display of elements with rows and columns. Consider the following example:

int x[3][3];

The two-dimensional array can be declared as above.

Figure 2.10 Array: element arrangement

The arrangement of array elements shown in Fig. 2.10 is only for the sake of understanding. Actually, the elements are stored in continuous memory locations.

A two-dimensional array is a collection of two one-dimensional arrays. The meaning of the first argument is in x [3]. [3] means the number of rows, i.e. number of one-dimensional arrays and the second argument indicates the number of elements. x [0][0] means the first element of the first row and column. Row number remains the same but column number changes. The number of rows and columns is called as the range of the array. A two-dimensional array clearly shows the difference between logical assumption and physical representation of data. The computer memory is linear and whatever may be the type of array—one, two or multi dimensional—it is stored in continuous memory locations. Fig. 2.11 explains the two-dimension array.

Figure 2.11 Storage of two-dimensional array

Example 2.11

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

Solution

# include <stdio.h>

# include <conio.h>

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 this program’s output, you can see that the memory addresses displayed are in sequence and it is true that elements of two-dimensional arrays are stored in successive memory locations. The one-dimensional array can be accessed using a single loop. However, for two-dimensional arrays, two loops are required for the row and column. The inner loop helps to access the row-wise elements and the outer loop changes the column number; just as a one-dimensional array base address can be stored in a pointer. Consider the following program.

Example 2.12

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

Solution

# include <stdio.h>

# include <conio.h>

main ()

{

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

clrscr();

p=&num[0][0];

printf("Elements Address");

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

printf("\n%3d %9u",*(p+j),(p+j));

}

OUTPUT

Elements

Address

4

65490

5

65492

6

65494

7

65496

Explanation This program is the same as the last one. But the point to note here is that to store the base address of a twodimensional array, it is not enough to mention the array; in addition, subscript number and address operation should also be mentioned. Only then will the compiler accept the statement; otherwise, the compiler flags an error message. For a one-dimensional array, an array name is sufficient, but onwards we have to mention the element number with the address operator.

2.5.1 Insert Operation with Two-dimensional Array

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

Example 2.13

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

Solution

# include <stdio.h>

# include <conio.h>

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 a number & position to insert: ");

scanf ("%d %d",&e,&at);

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

{

      *p=*(p‒1);

      p‒;

}

*p=e;

p=&num[0][0];

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

printf (" %d ",*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 the successive memory locations. A pointer can dereference to get successive memory location of memory. In this way, elements of the 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 a pointer.

Consider the statement p=&num [0][0]; used to store base address (address of 0th element of the array) of an array. Later in this program the array is not accessed by its name and corresponding row column numbers. The total capacity of the array of storing elements is 25 as per the declaration. The user is asked to enter the number of elements he wants to enter. The entered value is stored in the variable n through the scanf () statement. Thus, by 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 the variables ( scanf (“%d %d”,&e,&at);), variables e & at.

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

When the loop ends, the entered element is assigned to * (*p=e;). The ex-element is already shifted to the next position. Thus, finally the list of latest elements is displayed. The Fig. 2.12 (a) and (b) shows the insertion of element.

2.5.2 Delete Operation with Two-dimensional Array

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

Figure 2.12 Insertion of element

Example 2.14

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

Solution

# include <stdio.h>

# include <conio.h>

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 position 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 position to delete: 5

1 2 3 4 6 7

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

Figure 2.13 Deletion of element

2.6 THREE- OR MULTI-DIMENSIONAL ARRAYS

A three-dimensional array can be thought of as array of arrays. Consider the following program:

Example 2.15

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

Solution

# include <stdio.h>

# include <conio.h>

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 this example, a threedimensional array is initialized. The three loops are used to access the elements. The logic of accessing the elements is same as in the case of two-dimensional array. From the output obtained, we can say that elements of multi-dimensional array are stored in continuous memory locations.

2.7 STRINGS

The collection of characters, digits and symbols enclosed within quotation marks are called as strings. Strings are always declared as character array. Like other type of arrays, the elements of character array are also stored in continuous memory location. Each character occupies one byte in memory. One different thing about strings is that, the compiler automatically adds NULL (‘\0’) character at the end of the string. This character is used to detect the end of the string. The declaration of string can be done as follows. The Fig. 2.14 shows how the name is stored in the array.

char name[6]= "KAMAL";

Figure 2.14 Storing name in array

While declaring character array the declaration of NULL character should be taken into account. Therefore, the above array is declared of 6 sizes out of which five characters are stored first, then NULL character is stored at the end.

Example 2.16

Write a program to declare, initialize character array and display the string.

Solution

# include <stdio.h>

# include <conio.h>

main ()

{

char name[6]="kamal";

clrscr();

printf ("%s",name);

}

OUTPUT

Kamal

Explanation In this program a character array is declared and initialized with string “kamal”. Here, the array limit is declared for 6 characters and total six characters are stored including NULL character. Using printf () statement, string is displayed. Instead of 6 if limit is declared of 5, there is no place to insert NULL character and therefore the string will not be displayed properly.

Example 2.17

Write a program to encrypt a name and decrypt it.

Solution

# include <stdio.h>

# include <conio.h>

main ()

{

  char name[10],iname[10],dname[10];

  int i=0,y;

clrscr();

printf ("\nEnter the name:-");

scanf("%s",name);

while(name[i]!='\0')

{

iname[i]=name[i]+3;

i++;

}

iname[i++]='\0';

printf("\nThe encrypted name is:- %s",iname);

i=0;

while(iname[i]!='\0')

{

dname[i]=iname[i]‒3;

i++;

}

dname[i++]='\0';

printf("\nThe decrypted name is:- %s",dname);

}

OUTPUT:

Enter the name:-amit

The encrypted name is:- dplw

The decrypted name is:- amit

Example 2.18

Write a program to display the string and determine end of the string by NULL character.

Solution

# include <stdio.h>

# include <conio.h>

main ()

{

char arr[]={'A','B','C','D','E','\0'};

int j=0;

clrscr();

printf("Characters Address");

while (arr[j]!='\0')

{

printf ("\n %3c %9u",arr[j],&arr[j]);

j++;

}

}

OUTPUT

 

Characters

Address

A

65492

B

65493

C

65494

D

65495

E

65496

Explanation In this program a character array is declared and initialized. In the initialization, a NULL character is also initialized. The condition given in the while loop tests for NULL character. If it finds, the while loop is terminated, otherwise a character is displayed. We can also find that the characters are stored in successive memory locations.

Example 2.19

Write a program to display ASCII numbers, corresponding characters, and its encryption.

Solution

# include <stdio.h>

# include <conio.h>

# include <process.h>

main ()

{

int i, p=65;

char name[10];

clrscr();

printf ("\n Display the ASCII numbers, characters and encrypted characters:-");

printf("\nASCII no. Characters Encrypted characters");

for (p=65;p<=80;p++)

printf( "\n%5d %10c %12c",p,p,p+3);

printf ("\nEnter the string for encryption:- ");

scanf("%s",name);

printf ("The string after encryption:- ");

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

{

if(name[i]=='\0')

exit(1);

printf("%c",name[i]+3);

}

}

OUTPUT:

Display the ASCII numbers, characters and encrypted characters:-

 

ASCII no.
Characters
Encrypted characters
65
A
D
66
B
E
67
C
F
68
D
G
69
E
H
70
F
I
71
G
J
72
H
K
73
I
L
74
J
M
75
K
N
76
L
O
77
M
P
78
N
Q
79
O
R
80
P
S

Enter the string for encryption:- apple

The string after encryption:- dssoh

Explanation In this program the first for loop is starting from 65 to 80 for displaying the corresponding ASCII numbers, its characters, and encrypted characters. Second for loop is used for the encryption of the string which is entered in ‘name[]’.

Example 2.20

Write a program to enter the string for packet formation. Enter the size of the packet and display the contents of all packets.

Solution

# include<stdio.h>

# include <conio.h>

main ()

{

char message[50];

int f=0,i,np=0,pack;

clrscr();

printf("\nEnter the message:- ");

scanf("%s",message);

printf("Enter the size of packet:- ");

scanf("%d",&pack);

while(message[f]!='\0')

{

printf("\nPacket %d contains:- ",np+1);

for(i=0;i<pack;i++,f++)

{

if(message[f]=='\0')

break;

printf("%c",message[f]);

}

printf(":- %d characters",i);

np++;

}

printf("\nTotal packets:- %d",np);

}

OUTPUT:

Enter the message:- keepyourmindfreshforgoodprogramming

Enter the size of packet:- 5

Packet 1 contains:- keepy:- 5 characters

Packet 2 contains:- ourmi:- 5 characters

Packet 3 contains:- ndfre:- 5 characters

Packet 4 contains:- shfor:- 5 characters

Packet 5 contains:- goodp:- 5 characters

Packet 6 contains:- rogra:- 5 characters

Packet 7 contains:- mming:- 5 characters

Total packets:- 7

Explanation At first, the message without space is entered by the keyboard. Then, the packet size is to be specified. Fragmentation of data stream into packets is done with while loop. The end of the string is detected by using ‘\0’. While fragmentation, the characters are counted. On encountering ‘\0’ character the while loop is stopped by break statement. At the end of the program the total packets are printed.

2.8 ARRAY OF STRUCTURES

We have already studied structure in the first chapter. We also know that array is a homogeneous data structure and structure is a non-homogenous data structure. By declaring an array of structure objects, we can make combination of data structure of different types. However, we cannot create an array of non-homogenous type as such an array will also be homogenous type. Because all the elements are of the same type, i.e. structure type. The following program explains array of structure.

Example 2.21

Write a program to read display data using array of structure.

Solution

# include <stdio.h>

# include <conio.h>

main ()

{

struct item

{

   int codeno;

   int price;

};

int j;

struct item a[2];

clrscr();

printf ("\n Enter Codeno, Price\n ");

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

scanf ("%d %d",&a[j].codeno,&a[j].price);

printf ("\n Codeno Price ");

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

printf ("\n %d %d",a[j].codeno,a[j].price);

}

OUTPUT

 

Enter
Codeno,
Price
 
002
541
 
003
125
Codeno
Price
2
541
3
125

Explanation In this program, structure item is defined with two numeric fields, i.e. codeno and price. An array of structure item type a[2] is declared. Using for loop data read and displayed.

2.9 DRAWBACKS OF LINEAR ARRAYS
  1. The number of elements, which is to be stored in an array, must 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.
2.10 SPARSE MATRICES AND DENSE MATRICES

A sparse matrix is a two-dimensional array in which most of the elements are null. Figs. 2.15 (a) and 2.15 (b) indicate sparse and dense matrices. The matrix, which is not a sparse matrix, is called dense matrix. One cannot exactly determine the boundary between sparse and dense matrix. The sparse matrices are very useful in various applications. In sparse matrices, memory is wasted because the NULL values are stored and hence to overcome wastage of memory a mechanism must be followed. One of the mechanism is linked list, which will be discussed in detail in Chapter 6.

Figure 2.15 Sparse matrices and Dense matrices

The classification of sparse matrices is shown below in the Fig. 2.16.

Figure 2.16 Types of sparse matrices

2.10.1 Upper Triangular Matrices

The upper matrix is a type of triangular matrix, which is also a type of sparse matrix. A sparse matrix is a matrix in which maximum of the elements are zero. The upper matrix is also of two kinds: upper left and upper-right as shown in Fig. 2.18 and Fig. 2.17 respectively.

Figure 2.17 Upper right triangular

In Fig. 2.17, a triangle of null elements and non-element is present. The triangle of NULL elements is present the left side and the triangle of non-element is present on the right side.

Example 2.22

Write a program to initialize and display upper right triangular matrix.

Solution

# include <stdio.h>

# include <conio.h>

main ()

{

int j,k,urt[5][5]={ 0,4,3,2,1,

    0,0,3,2,1,

    0,0,0,2,1,

    0,0,0,0,1,

    0,0,0,0,0,

                        };

clrscr();

printf ("\n UPPER RIGHT TRIANGULAR\n");

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

{

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

printf ("%d",urt[j][k]);

printf ("\n");

}

}

OUTPUT

UPPER RIGHT TRIANGULAR

0 4 3 2 1

0 0 3 2 1

0 0 0 2 1

0 0 0 0 1

0 0 0 0 0

Explanation In this program an array is initialized and the NULL elements form an upper right triangular matrix and it is displayed. Fig. 2.18 shows the upper left triangular matrix.

Figure 2.18 Upper left triangular

Example 2.23

Write a program to initialize and display upper left triangular.

Solution

# include <stdio.h>

# include <conio.h>

main ()

{

int j,k,ult[5][5]={ 1,2,3,4,0,

    1,2,3,0 ,0,

    1,2,0 ,0,0,

    1,0,0,0,0,

    0,0,0,0,0,

                        };

clrscr();

printf ("\n UPPER LEFT TRIANGULAR\n");

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

{

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

    printf (" %d ",ult[j][k]);

    printf ("\n");

}

}

OUTPUT

UPPER LEFT TRIANGULAR

1 2 3 4 0

1 2 3 0 0

1 2 0 0 0

1 0 0 0 0

0 0 0 0 0

2.10.2 Lower Triangular Matrices

Figure 2.19 Lower-left triangular

Example 2.24

Write a program to display lower left triangular matrix.

Solutions

# include <stdio.h>

# include <conio.h>

main ()

{

int j,k,llt[5][5]={ 0,0,0,0,0,

    1,0,0,0,0,

    1,2,0,0,0,

    1.2.3.0. ,0,

    1,2,3,4,0,

                            };

clrscr();

printf ("\n LOWER LEFT TRIANGULAR\n");

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

{

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

    printf (" %d ",llt[j][k]);

    printf ("\n");

}

}

OUTPUT

LOWER LEFT TRIANGULAR

0 0 0 0 0

0 0 0 0 0

1 2 0 0 0

1 2 3 0 0

1 2 3 4 0

Explanation In this program an array llt [][] is initialized. The array is initialized in such a way that maximum elements are NULL and hence, it is sparse matrix. The NULL elements form a triangular at lower left side. Hence, this matrix is called lower left triangular matrix. The Fig. 2.19 shows the lower left triangular matrix.

Figure 2.20 Lower right triangular

Example 2.25

Write a program to initialize and display lower right triangular matrix.

Solution

# include <stdio.h>

# include <conio.h>

main ()

{

int j,k,lrt[5][5]={ 0,0,0,0,0,

        0,0,0,0,1,

        0,0,0,2,1,

        0,0,3,2,1,

        0,4,3,2,1,

                                };

clrscr();

printf ("\n LOWER RIGHT TRIANGULAR\n");

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

{

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

    printf (" %d ",lrt[j][k]);

    printf ("\n");

}

}

OUTPUT

LOWER RIGHT TRIANGULAR

0 0 0 0 0

0 0 0 0 1

0 0 0 2 1

0 0 3 2 1

0 4 3 2 1

Explanation This program is the same as the last one and displays lower right triangular matrix. Fig. 2.20 is an example of lower right triangular matrix.

Example 2.26

Write a program to find whether the given matrix is lower right triangular matrix or not.

Solution

# include <stdio.h>

# include <conio.h>

int matrix[3][3];

main ()

{

clrscr();

input();

display();

lowe_r();

}

input ()

{

int n,j,k;

printf("\n Enter elements for matrix ");

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

{

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

scanf ("%d",&matrix[j][k]);

}

return 0;}display ()

{

int n,j,k;

printf("\n Elements of matrix\n");

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

{

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

printf ("%4d",matrix[j][k]);

printf("\n"); }

return 0;}

lowe_r ()

{

int nj,k,u=3; char b=' ';

printf("\n Elements of matrix\n");

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

{

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

{

printf ("%4d",matrix[j][k]);

if (matrix[j][k]==0)

b='Y'; else b='N';

}

u−−;

printf("\n");

}

if (b=='Y')

puts ("\n The given matrix is lower right triangular matrix");

else

puts ("\n Not a sparse matrix");

return 0;

}

OUTPUT

Enter elements for matrix 0 0 0 0 0 0 0 1 5

Elements of matrix

0 0 0

0 0 0

0 1 5

Elements of matrix

0 0 0

0 0

0

The given matrix is lower right triangular matrix.

Explanation In this program matrix [3][3] is declared. Through input () function, elements are entered. The display () function displays the elements of the matrices. Through use of lowe_r () function, elements of rows 1st, 2nd and 3rd are checked. The numbers of elements are 3,2 and 1, respectively. If these elements are NULL, the matrix is lower right triangular matrix.

In some of the earlier programs, arrays, i.e. matrix, are initialized and displayed. This can be implemented easily. However, in the above program, elements are entered during program execution. Hence, few additional statements are required.

Figure 2.21 Diagonal matrices

In case of diagonal matrices, only diagonal elements are non-zero and other values are NULL as shown in the Fig. 2.21.

Example 2.27

Write a program to initialize and display diagonal matrix.

Solution

# include <stdio.h>

# include <conio.h>

main ()

{

int j,k,dgl[5][5]={ 1,0,0,0,0,

        0,2,0,0,0,

        0,0,3,0,0,

        0,0,0,4,0,

        0,0,0,0,5,

                                };

clrscr();

printf ("\n DIAGONAL MATRIX\n");

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

{

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

    printf (" %d ",dgl[j][k]);

    printf ("\n");

}

}

OUTPUT

DIAGONAL MATRIX

1 0 0 0 0

0 2 0 0 0

0 0 3 0 0

0 0 0 4 0

0 0 0 0 5

Explanation In this program an array is initialized in which diagonal elements are non-zero.

Figure 2.22 Tri-diagonal matrices

Example 2.28

Write a program to initialize and display tri-diagonal matrix.

Solution

# include <stdio.h>

# include <conio.h>

main ()

{

int j,k,dgl[5][5]={ 5,1,0,0,0,

        1,6,2,0,0,

        0,2,7,3,0,

        0,0,3,8,4,

        0,0,0,4,9,

                            };

clrscr();

printf ("\n DIAGONAL MATRIX\n");

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

{

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

    printf (" %d ",dgl[j][k]);

    printf ("\n");

}

}

OUTPUT

DIAGONAL MATRIX

5 1 0 0 0

1 6 2 0 0

0 2 7 3 0

0 0 3 8 4

0 0 0 4 9

Explanation In this program, tri-diagonal matrix is initialized and displayed as shown in Fig. 2.22.

2.11 ROW-MAJOR ARRAYS

Row-major implementation is a liberalization technique in which elements in an array are arranged row-wise. Elements are stored row by row as shown in Fig. 2.23.

Consider an array

int X[3][3];

Figure 2.23 Row-major array

Consider the following program.

Example 2.29

Write a program to implement an array by row-major method.

Solution

# include <stdio.h>

# include <conio.h>

main ()

{

int j,k,x[3][3];

clrscr();

printf ("\n Enter nine elements: ");

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

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

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

printf ("\n Row major array\n");

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

{

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

    printf (" %d ",x[j][k]);

printf ("row- [ %d ]\n"j+1);

}

}

OUTPUT

Enter nine elements: 7 8 9 4 5 2 1 5 9

Row major array

7 8 9 row- [ 1 ]

4 5 2 row- [ 2 ]

1 5 9 row- [ 3 ]

Explanation In this program two for loops are used. The elements are entered through the keyboard. The outer loop indicates row and inner loop indicates column. After finishing the execution of inner loop, outer loop is executed once. Thus, when one complete row is filled with elements, the outer loop is executed and it indicates next row, which is to be filled. Again, the inner loop is used to fill the elements. Thus, elements are stored row-by-row.

2.12 COLUMN-MAJOR ARRAYS

In column major array elements are stored column-by-column as shown in Fig. 2.24.

Figure 2.24 Column major array

Example 2.30

Write a program to implement an array by column major method.

Solution

# include <stdio.h>

# include <conio.h>

main ()

{

int j,k,x[3][3];

clrscr();

printf ("\n Enter nine elements: ");

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

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

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

printf ("\n Column major array\n");

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

{

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

    printf (" %d ",x[j][k]);

    printf("\n");

}

}

OUTPUT

Enter nine elements: 1 2 3 4 5 6 7 8 9

Column major array

1 4 7

2 5 8

3 6 9

Explanation In column major method the elements entered are stored column by column. The outer loop indicates column number and inner loop indicates row. When one complete column is filled, next column is considered for filling.

2.13 POINTERS AND ARRAYS

Array name by itself is an address or pointer. It points to the address of the first element (0th element of an array). The elements of the array together with their addresses can be displayed by using array name itself. Array elements are always stored in contiguous memory locations.

Programs in this regard are explained below.

Example 2.31

Write a program to display elements of an array. Start element counting from 1 instead of 0.

Solution

# include <stdio.h>

# include <conio.h>

main()

{

int x[]={2,4,6,8,10},k=1;

clrscr();

while (k<=5)

{

    printf ("%3d",k[x‒1]);

    k++;

}

}

OUTPUT:

2 4 6 8 10

Explanation Array element counting always starts from ‘O’. The element number is added in the base address and each element of an array is accessed. If one is subtracted from base address of an array, it points to the prior address of 0th element. By adding one to its reduced base address it is possible to start element counting from ‘1’.

Example 2.32

Write a program to display array element with their addresses using array name as a pointer.

Solution

# include <stdio.h>

# include <conio.h>

main()

{

int x[5]={2,4,6,8,10},k=0;

clrscr();

printf ("\nElement No. Element Address");

while (k<5)

{

    printf ("\nx[%d] = \t%8d %9u",k,*(x+k),x+k);

    k++;

}

}

OUTPUT:

 

Element No.

Element

Address

x[0]
2

4056

x[1]
4

4058

x[2]
6

4060

x[3]
8

4062

x[4]
10

4064

Explanation In this program variable ‘k’ acts as element number and its value varies from 0 to 4. When it is added with array name 'x', i.e. with address of the first element, it points to the consecutive memory location. Thus, element no., element, and their addresses are displayed.

 

OR

Example 2.33

Write a program to display array elements with their addresses using array name as a pointer.

Solution

# include <stdio.h>

# include <conio.h>

main()

{

int num[4]={10,25,35,45},i;

clrscr();

printf ("Element Address\n");

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

{

    printf("num[%d]=%d",i,*(num+i));

    printf ("%8u\n",num+i);

}

}

OUTPUT:

 

Element
Address

num[0] = 10

4062

num[1] = 25

4064

num[2] = 35

4066

num[3] = 45

4068

Explanation Here, the array name ‘num’ itself acts as a pointer to the array num []. The pointer ‘num’ provides address of first element and ‘*num’ gives value stored at that address. When ‘i’ is added with ‘num’, the equations *(num+i) and num+i show ‘i’ the element and its location, respectively.

Example 2.34

Write a program to access elements of array through different ways using pointer.

Solution

# include <stdio.h>

# include <conio.h>

main()

{

    int arr[5]={10,20,30,40,50},p=0;

    clrscr();

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

{

    printf ("Value of arr[%d]=",p);

    printf ("%d | ",arr[p]);

    printf ("%d | ",*(arr+p));

    printf ("%d | ",*(p+arr));

    printf ("%d |",p[arr]);

    printf (" address of arr[%d]=%u\n",p,&arr[p] );

}

}

OUTPUT:

Value of arr[0]=10 | 10 | 10 | 10 | address of arr[0]=4056

Value of arr[1]=20 | 20 | 20 | 20 | address of arr[1]=4058

Value of arr[2]=30 | 30 | 30 | 30 | address of arr[2]=4060

Value of arr[3]=40 | 40 | 40 | 40 | address of arr[3]=4062

Value of arr[4]=50 | 50 | 50 | 50 | address of arr[4]=4064

OUTPUT:

Value of arr[0]=10 | 10 | 10 | 10 | address of arr[0]=4056

Value of arr[1]=20 | 20 | 20 | 20 | address of arr[1]=4058

Value of arr[2]=30 | 30 | 30 | 30 | address of arr[2]=4060

Value of arr[3]=40 | 40 | 40 | 40 | address of arr[3]=4062

Value of arr[4]=50 | 50 | 50 | 50 | address of arr[4]=4064

Explanation In this program elements are displayed using different syntax, a. arr[p] b. *(arr+p)) c) *(p+arr)) d) p[arr]). The results of all of them would be the same.

  1. arr[p]: This statement displays various array elements. Here, ‘arr’ refers to the address and ‘p’ refers to the element number.
  2. *(arr+p): The arr+p is addition of constant with base address of the array. It shows address of pth element. The *(arr+p) points to the pth element of the array.
  3. *(p+arr): This statement is same as (b).
  4. p[arr]: This statement is same as (a). Here, ‘p’ refers to the element number and ‘arr refers to the base address. By varying ‘p’ and ‘arr’ the various elements of the array are displayed.

Example 2.35

Write a program to find sum of all the elements of an array. Use array name itself as a pointer.

Solution

# include <stdio.h>

# include <conio.h>

main()

{

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

    clrscr();

    printf ("Elements Values Address\n\n");

    while (i<5)

    {

        printf ("a[%d]\t%5d\t%8u\n",i,*(a+i),(a+i));

        sum=sum+*(a+i++);

    }

    printf ("\nSum of Array Elements = %d",sum);

}

OUTPUT:

 

Elements
Values
Address
a[0]
1

4056

a[1]
2

4058

a[2]
3

4060

a[3]
4

4062

a[4]
5

4064

Sum of Array Elements = 15

Explanation In this program array name 'a' acts as pointer and variable ‘i’ is used for referring element numbers. Using the/or loop and expressions *(a+i) and (a+i) various elements and their addresses are displayed respectively. In the ‘sum’ variable sum of all elements is obtained.

Example 2.36

Write a program to display the sum of squares and cubes of array elements using pointer.

Solution

# include <stdio.h>

# include <conio.h>

# include <math.h>

main()

{

    int b[]={1,2,3,4,5}j,sumsq=0,sumc=0;

    clrscr();

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

    {

        sumsq=sumsq+pow(*(j+b),2);

        sumc=sumc+pow(b[j],3);

    }

    printf ("\nSum of Squares of array elements: %d", sumsq);

    printf ("\nSum of Cubes of array elements: %d",sumc);

}

OUTPUT:

Sum of Squares of array elements: 55

Sum of Cubes of array elements: 225

Explanation In this program using pow() function square and cube of array elements are computed and added to variable ‘sumsq’ and ‘sumc’ respectively. Using printf() statement sum of square and cube of array elements are displayed.

Example 2.37

Write a program to copy elements of one array to another array using pointers.

Solution

# include <stdio.h>

# include <conio.h>

main()

{

    int so[]={10,20,30,40,50},*pb,ds[5],i;

    pb=so;

    clrscr();

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

    {

        ds[i]=*pb;

        pb++;

    }

printf ("Orignal Array Duplicated Array");

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

printf ("\n\t%d\t\t %d", so[i],ds[i]);

}

OUTPUT:

Original Array

Duplicated Array

10
10
20
20
30
30
40
40
50
50

Explanation In this program pointer ‘pb’ contains base address of array so []. In the for loop pointer ‘pb’ is assigned to corresponding element of array ds [] and then incremented. After increment it points to the address of next element of the array. Thus, all the elements are copied to ds [] array.

Example 2.38

Write a program to copy one array into another array. Order of elements of second array should be opposite to first array.

Solution

# include <stdio.h>

# include <conio.h>

main()

{

int arr1[]={15,25,35,45,55},arr2[5],i;

clrscr();

printf ("\nOrigonal Array Duplicate Array");

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

{

arr2[i]=*(arr1+4-i);

printf ("\n\t%d \t\t%d",arr1[i],arr2[i]);

}

}

OUTPUT:

Original Array

Duplicated Array

15
55
25
45
35
35
45
25
55
15

Explanation The logic of the program is the same as the previous one. Here, instead of starting from base address of the array, address of last element of the array is selected first. Using for loop, the addresses are read in the reverse order and their contents are copied to destination array arr2 [].

2.14 POINTERS AND TWO-DIMENSIONAL ARRAYS

A matrix can represent two-dimensional elements of an array. Here, the first argument is row number and second is column number. To display the elements of two-dimensional array using pointer it is essential to have operator as pre-fix with array name followed by element numbers, otherwise compiler shows an error.

Example 2.39

Write a program to display array elements and their address using pointers.

Solution

# include <stdio.h>

# include <conio.h>

main()

{

int ij=1,*p;

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

clrscr();

printf ("\tElements of An Array with their addresses\n\n");

p=&a[0][0];

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

{

    printf ("%5d [%5u ]",*(p),p);

    p++;

if (j==3)

{

    printf ("\n");

    j=0;

   }

  }

}

OUTPUT:

Elements of an Array with their addresses.

1 [4052] 2 [4054] 3 [4056]

4 [4058] 5 [4060] 6 [4062]

7 [4064] 8 [4066] 9 [4068]

Explanation In this program two-dimensional array is declared and initialized. The base address of array is assigned to integer pointer ‘p’. While assigning base address of two-dimensional array, ‘&’ operator is to be prefixed with array name followed by element numbers are necessary otherwise compiler shows an error. The statement p=&a[0][0] is used in this context. The pointer ‘p’ is printed and incremented in for loop till it prints entire array elements. The if statement splits a line when three elements in each row are printed.

 

OR

Example 2.40

Write a program to display array elements and their address. Use array name itself as a pointer.

Solution

# include <stdio.h>

# include <conio.h>

main()

{

int i;

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

clrscr();

printf ("\tElements of An Array with their addresses.\n\n");

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

{

printf ("%8u",&a[0][0]+i);

printf (" [%d]",*(&a[0][0]+i));

if (i==2 || i==5)

printf ("\n");

}

}

OUTPUT:

Elements of an Array with their addresses.

1 [4052] 2 [4054] 3 [4056]

4 [4058] 5 [4060] 6 [4062]

7 [4064] 8 [4066] 9 [4068]

Explanation The logic of the program is the same as the previous one. The only difference is that the array name itself is used as pointer. The if statement inserts a line after displaying every three elements.

2.15 ARRAY OF POINTERS

So far, we have studied array of different standard data types such as array of int, float, characters, etc. In the same way the ‘C’ language also supports array of pointers. It is nothing but a collection of addresses. Here, we store address of variables for which we have to declare array as pointer.

Example 2.41

Write a program to store addresses of different elements of an array—using array of pointers.

Solution

# include <stdio.h>

# include <conio.h>

main()

{

int *arrp[3];

int arrl[3]={5,10,15},k;

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

arrp[k]=arrl+k;

clrscr();

printf ("\n\tAddress Element\n");

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

{

   printf ("\t%u",arrp[k]);

   printf ("\t%7d \n",*(arrp[k]));

}

}

OUTPUT:

Address Element

4060       5

4062      10

4064      15

Explanation In this program *arrp[3] is declared as array of pointer. Using first for loop addresses of various elements of array ‘arr []’ are assigned to ‘*arrp[]’. The second for loop picks up addresses from '*arrp[]' and displays the value present at those locations. Here, each element of ‘*arrp[]’ points to respective element of array ‘arr[]’.

 

Table 2.1 Array of pointers in memory

Example 2.42

Write a program to display address of elements and pointers.

Solution

# include <stdio.h>

# include <conio.h>

main()

{

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

int *p[5],i;

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

p[i]=a+i;

clrscr();

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

{

   printf ("\n\t%d at location",*(*p+i));

   printf ("\t%u at location ",*(p+i));

   printf ("%u",p+i);

}

printf ("\n\n Integer requires 2 bytes, address require 4 bytes");

}

OUTPUT:

0 at location 4036 at location 4046

1 at location 4038 at location 4050

2 at location 4040 at location 4054

3 at location 4042 at location 4058

4 at location 4044 at location 4062

Integer requires 2 bytes, address requires 4 bytes

Explanation In this program the first for loop assigns addresses of elements of integer array to pointer array. The first printf() statement prints element, the second displays address of element and the third displays address of the address, i.e. address of the pointer. Thus, it is clear from the above example that integer requires two bytes and pointer requires four bytes.

2.16 POINTERS AND STRINGS

Example 2.43

Write a program to read string from keyboard and display it using character pointer.

Solution

#include <stdio.h>

#include <conio.h>

main()

{

char name[15],*ch;

printf ("Enter Your Name:");

gets(name);

ch=name;

/* store base address of string name */

while (*ch!='\0')

{

   printf ("%c",*ch);

   ch++;

}

}

OUTPUT:

Enter Your Name: KUMAR

KUMAR

Explanation Here, the address of 0th element is assigned to character pointer ‘ch’. In other words, base address of string is assigned to ‘ch’. The pointer ‘*ch’ points to the value stored at that memory location and it is printed through printf() statement. After every increment of ‘ch’ the pointer goes to the next character of the string. When it encounters NULL character the while loop terminates the program.

Example 2.44

Write a program to find length of a given string including and excluding spaces using pointers.

Solution

# include <stdio.h>

# include <conio.h>

main()

{

char str[20],*s;

int p=0,q=0;

clrscr();

printf ("Enter String:");

gets(str);

s=str;

while (*s!='\0')

{

   printf ("%c",*s);

   p++;

   s++;

   if (*s==32) /* ASCII equivalnet of ' ' (space)is 32*/

   q++;

}

printf ("\nLength of String including spaces: %d",p);

printf ("\nLength of String excluding spaces: %d",p-q);

}

OUTPUT:

Enter String: POINTERS ARE EASY

POINTERS ARE EASY

Length of String including spaces: 17

Length of String excluding spaces: 15

Explanation Here, the address of 0th element is assigned to character pointer ‘ch’. In other words, base address of string is assigned to ‘ch’. The pointer ‘*ch’ points to the value stored at that memory location and it is printed through printf() statement. After every increment of ‘ch’ the pointer goes to the next character of the string. When it encounters NULL character the while loop terminates the program.

Example 2.45

Write a program to find length of a given string including and excluding spaces using pointers.

Solution

# include <stdio.h>

# include <conio.h>

main()

{

char str[20],*s;

int p=0,q=0;

clrscr();

printf ("Enter String:");

gets(str);

s=str;

while (*s!='\0')

{

   printf ("%c",*s);

   p++;

   s++;

   if (*s==32) /* ASCII equivalent of ' ' (space)is 32*/

   q++;

}

printf ("\nLength of String including spaces: %d",p);

printf ("\nLength of String excluding spaces: %d",p‒q);

}

OUTPUT:

Enter String: POINTERS ARE EASY

POINTERS ARE EASY

Length of String including spaces: 17

Length of String excluding spaces: 15

Explanation This program is the same as the previous one. Here, the counter variables ‘p’ and ‘q’ are incremented to count number of characters and spaces found in the string. The ASCII value of space is 32. Thus, at the end of the program both the variables are printed.

Example 2.46

Write a program to interchange elements of character array using pointer.

Solution

# include <stdio.h>

# include <conio.h>

main()

{

char *names[]={

"kapil",

"manoj",

"amit",

"amol",

"pavan",

"mahesh"

};

char *tmp;

clrscr();

printf ("Original: %s %s",names[3],names[4]);

tmp=names[3];

names[3]=names[4];

names[4]=tmp;

printf ("\nNew: %s %s",names[3],names[4]);

}

OUTPUT:

Original: amol pavan

New: pavan amol

Explanation In this program character array *names [] is declared and initialized. Another character pointer *tmp is declared. The destination name that is to be replaced is assigned to variable ‘*tmp’. The destination name is replaced with source name and the source name is replaced with *tmp variable. Thus, using simple assignment statements two names are interchanged.

Example 2.47

Write a program to read two strings through the keyboard. Compare these two strings character by character. Display the similar characters found in both the strings and count the number of dissimilar characters.

Solution

# include <stdio.h>

# include <conio.h>

# include <string.h>

main()

{

char str1[20],str2[20],l,*a,*b;

int c=0;

clrscr();

   printf ("\n Enter First String:");

   gets(str1);

   printf ("\n Enter Second String:");

   gets(str2);

a=str1;

b=str2;

printf ("\n Similar Characters Found in Both String.");

   while (*a!='\0')

   {

   if (stricmp(*a,*b)==0)

{

printf ("\n\t%c \t%c",*a,*b);

l++;

}

else

   c++;

   a++;

   b++;

   }

   if (c==0)

   printf ("\n The Strings are Identical.");

   else

   printf ("\nThe Strings are different at %d places.",c);

   printf ("\n The String Characters are similar at %d places.",l);

}

OUTPUT:

Enter First String: SUNDAY

Enter Second String: MONDAY

Similar Characters Found in Both Strings.

    N    N

    D    D

    A    A

    Y    Y

The Strings are different at 2 places.

The String Characters are similar at 4 places.

Explanation In this program two strings are entered in the character array str1 [] and str2 []. Their base addresses are assigned to pointer '*a' and '*b'. In the while loop two pointers are compared using stricmp () function. If the characters of two strings are same the counter variable ‘l’ is incremented and characters are printed. Otherwise, the counter ‘c’ is incremented. This job is done in the if statement. The character pointers ‘a’ and ‘b’ are incremented throughout the while loop to obtain the successive characters from both the strings. The last if statement displays a message stating that the given string is different or identical depending on the value of ‘c’.

Example 2.48

Write a program to enter three characters, using pointers. Use the memcmp () function for comparing the three characters. In case the entered characters are same, display the message “the characters are same”; otherwise, indicate their appearance before or after one another or display the status of characters in alphabetical order. (The memcmp () function compares a specified number of characters from two buffers.)

Solution

#include <stdio.h>

#include <conio.h>

#include <string.h>

#include <process.h>

main()

{

char x,y,z,*xp,*yp,*zp;

int stat=0;

clrscr();

printf ("Enter Three Characters");

scanf ("%c %c %c",&x,&y,&z);

xp=&x,yp =&y, zp =&z;

stat = memcmp(yp, xp, strlen(yp));

if (*xp==*yp)

{

   printf ("\n1st and 2nd Character are same.\n");

   goto next;

}

   if (stat > 0)

   printf("2nd Character appears after the 1st Character in Alphabetic.\n");

   else

   printf("2nd Character appears before the first Character in Alphabetic \n");

next:

   stat = memcmp(yp,zp, strlen(yp));

   if (*yp==*zp)

   {

   printf ("\n2nd and 3rd Character are same.");

   exit(1);

   }

   if (stat > 0)

   printf(”2nd Character appears after the 3rd Character in Alphabetic. \n");

   else

   printf(”2nd Character appears before 3rd Character in Alphabetic. \n");

}

OUTPUT:

Enter Three Character C C A

1st and 2nd Character are same.

2nd Character appears after the 3rd Character in Alphabetic.

Explanation In this program three characters are entered in the character variable ‘x’,‘y’ and ‘z’ and their base addresses are stored in the pointers ‘xp’,‘yp’ and ‘zp’, respectively. The function memcmp () is used to compare two pointers for specified length. If first two characters are same, a message is displayed and control goes to next label. In the next label, second and third characters are compared. Using the value of variable ‘stat’ locations of characters are decided.

Example 2.49

Write a program to compare two strings irrespective of case. Compare the characters at the specific position. If they are same display ‘The characters are same at that position”.

Solution

#include <stdio.h>

#include <string.h>

# include <conio.h>

main()

{

char *buf1 = "computer";

char *buf2 = "comp ter";

int stat;

stat = memicmp(buf1, buf2,4);

clrscr();

printf("The Characters up to 4th position are ");

if (stat) */ if stat is non zero then prints 'not' otherwise 'same'.t */

printf("not ");

printf("same\n");

}

OUTPUT:

The Characters up to 4th position are same.

Explanation The memicmp () function compares two strings for specified number of characters. It returns zero if both the strings are same up to specified length of characters. Otherwise, non-zero value will be returned. Depending upon the value it returns, the if statement displays respective message.

Summary
  1. Array is a very popular and useful data structure used to store data elements in successive manner. Array is a linear and homogenous data structure. Homogenous means same types of elements are stored in it. It may be non-homogenous if structure is associated with it.
  2. One-dimensional arrays having only one row of elements and elements are stored in successive memory locations.
  3. The various operations carried out with arrays are insertion, deletion, searching, sorting, etc.
  4. Two-dimensional arrays can be thought of as rectangular display of elements with rows and columns.
  5. A three-dimensional arrays can be thought of as array of arrays.
  6. The collection of characters, digits, and symbols enclosed within quotation marks are called strings. Strings are always declared as character array. Like other type of arrays, elements of character array are also stored in continuous memory location. Each character array occupies one byte in memory. One different thing about strings is that, the compiler automatically adds NULL (‘\0’) character at the end of string.
Exercises
  1. Answer the following questions:
    1. What are arrays?
    2. How are elements of array stored?
    3. What are one-dimensional arrays?
    4. What are two-dimensional arrays?
    5. Explain multi-dimensional array.
    6. What are strings? How are they declared?
    7. What is NULL character?
    8. Explain various operations with arrays.
    9. What are sparse matrices?
    10. Distinguish between character and integers arrays.
    11. Can we store values and addresses in the same array?
    12. Explain the difference between row major and column major array.
  2. Attempt following programs:
    1. Write a program to declare one-dimensional float type array. Display elements with memory addresses.
    2. Write a program to read ten integers in an array and find the number of even and odd numbers in it.
    3. Write a program to input a number containing five digits. Obtain cube of each digit and display the cubes of all digits on the screen.
    4. Read the marks in physics, chemistry and mathematics obtained by ten students. Display the top three students with their total marks.
    5. Write a program to enter a four-digit number using array and arrange it in the reverse order.
    6. Write a program to demonstrate use of two-dimensional array.
    7. Write a program to access elements of an array using another pointer.
    8. Write a program to declare a character array. Initialize with the string and display the contents.
    9. Write a program to demonstrate the use of multi-dimensional array.
    10. Write a program to create array of structure objects. Read and display the data.
    11. Write a program to delete and insert an element in an array.
    12. Write a program to find whether the given matrix is lower-left matrix or not.
    13. Write a program to enter and store elements in an array. Display only diagonal elements.
    14. Write a program to find whether the given matrix is sparse matrix or dense matrix.
  3. Select the appropriate option for each of the following questions:
    1. Array elements are stored in
      1. successive memory locations
      2. random memory locations
      3. both (a) and (b)
      4. none of the above.
    2. Accessing all elements of the array is known as
      1. transverse
      2. insertion
      3. deletion
      4. listing.
    3. Merging of array elements means
      1. combining two or more arrays
      2. addition of elements of two arrays
      3. interchanging elements of two arrays
      4. none of the above.
    4. Following one operation cannot be performed on arrays
      1. merging
      2. insertion
      3. deletion
      4. memory re-allocation.
    5. Base address means
      1. address of 0th element
      2. address of array name
      3. address of last element
      4. none of the above.
    6. Array elements are stored in
      1. random memory locations
      2. sequential memory locations
      3. both of the above.
    7. A character array always ends with
      1. comma(,)
      2. question mark ( ? )
      3. null character ( \0 )
      4. Full stop (.).
    8. Arrays can not be initialized if they are
      1. automatic
      2. static
      3. external
      4. none of the above.
    9. All the elements in the array must be
      1. initialized
      2. defined
      3. none of the above.
  4. What will be the output of the following programs?
    1. #include <stdio.h>

      #include <conio.h>

      main()

      {

      char nam[10],*h;

      printf ("Enter Your Name:");

      scanf("%s",&nam);

      h=nam;

      while (*h!='\0')

      {

      printf ("%c",*h);

      h++;

      }

      }

       

    2. # include <stdio.h>

      # include <conio.h>

      main()

      {

      int x[5]={12,42,26,18,80},a=0;

      clrscr();

      while (a<5)

      {

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

      a++;

      }

      }

       

    3. # include <stdio.h>

      # include <conio.h>

      main ()

      {

      int i;

      char name[10];

      clrscr();

      scanf("%s",name);

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

      {

      if(name[i]=='\0')

      exit(1);

      printf("%c",name[i]+3);

      }

      }

       

    4. # include <stdio.h>

      # include <conio.h>

      main ()

      {

      char name[6]="DATA";

      clrscr();

      printf("%c",name);

      printf ("%s",name);

      }

       

    5. # include <stdio.h>

      # include <conio.h>

      int main ()

      {

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

      clrscr();

      p=n;

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

      printf ("\n%d", *(p+j));

      }

       

    6. # include <stdio.h>

      # include <conio.h>

      main ()

      {

      int m[5]={0}j;

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

      printf ("\n%d",m[j]);

      }

       

    7. # include <stdio.h>

      # include <conio.h>

      main()

      {

      int x[5]={2,27,6,86,60},a;

      clrscr();

      for(a=5;a>=0;a−−)

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

      }

       

    8. # include <stdio.h>

      # include <conio.h>

      main (){

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

      int i;

      clrscr();

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

      printf ("%c",a[i]);

      }

       

    9. # include <stdio.h>

      # include <conio.h>

      main (){

      char a[5]={65,66,67,68,69};

      int i;

      clrscr();

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

      printf ("%c",a[i]);

      }