Back to Study material
CCP


Unit 7


Arrays


Array is defined as a collection of elements of same data type. Hence it is also called as homogeneous variable. Total number of elements in array defines size of array. Position of element in an array defines index or subscript of particular element. Array index always starts with zero.

 

  1. One Dimensional Array:

The array which is used to represent and store data in a linear form is called as 'single or one dimensional array.'

Syntax:

Data-type array_name[size];

 

Example 2:

 

Int a[3] = {2, 3, 5};

Char ch[10] = "Data" ;

Float x[3] = {2.5, 3.50,489.98} ;

 

Total Size of an array(in Bytes) can be calculated as follows:

 

Total size(in bytes) = length of array * size of data type

 

In above example, a is an array of type integer which has storage size of 3 elements. One integer variable occupies 2 bytes. Hence the total size would be 3 * 2 = 6 bytes.

Memory Allocation :

 

5

10

15

2

4

 

Index/Subscript                   0  1           2                     3                         4

 

Address                     1000                   1002                  1004                  1006                  1008

 

Fig 1 : Memory allocation for one dimensional array

 

P1:   Program to display all elements of 1-D array.

#include<stdio.h>
#include<conio.h>
void main()
{
int a[20];
int n,i;
printf("\n Enter the size of array :");
scanf("%d",&n);
printf("size of array is %d",n);
printf("\n Enter Values to store in array one by one by pressing ENTER :");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n The Values in array are..");


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

 

 

P2: Program to copy 1-D array to another 1-D array

 

#include <stdio.h>

#include<conio.h>

 

Void main()

{

Int n, i, j, a[100], b[100];// a is original array and b is copied array

 

Printf("Enter the number of elements in array a\n");

Scanf("%d", &n);

 

Printf("Enter the array elements in a\n");

 

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

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

 

/*

Copying elements from array a into array b */

 

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

b[i] = a[i];

 

/*

Printing copied array b

.

*/

 

Printf("Elements of array b are\n");

 

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

Printf("%d\n", b[i]);

 

Getch();

}

 

Output:

 

P3:Program to find reverse of 1-D array

#include <stdio.h>

#include<conio.h>

 

Void main()

{

Int n, i, j, a[100], b[100];// a is original array and b is reversed array

 

Printf("Enter the number of elements in array\n");

Scanf("%d", &n);

Printf("Enter the array elements\n");

 

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

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

 

/*

* Copying elements into array b starting from end of array a

*/

For (i = n - 1, j = 0; i >= 0; i--, j++)

b[j] = a[i];

/*

Printing reversed array b

.

*/

Printf("Reverse array is\n");

 

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

Printf("%d\n", a[i]);

 

Getch();

}

 

Output:

 

 


 

1-D array has 1 row and multiple columns but multidimensional array has of multiple rows and multiple columns.

 

Two Dimensional array:

 

It is the simplest multidimensional array. They are also called as matrix.

 

Declaration:

Data-type array_name[no.of rows][no. Of columns];

 

Total no of elements= No.of rows * No. Of Columns

 

Example 3: int a[2][3]

This example illustrates two dimensional array a of 2 rows and 3 columns.

 

Col 0  Col 1  Col 2

 

Row 0

a[0][0]

 

a[0][1]

 

a[0][2]

 

a[1][0]

 

a[1][1]

 

a[1][2]

 

 

Row 1

Fig.2: Index positions of elements of a[2][3]

 

Total no of elements: 2*3=6

Total no of bytes occupied: 6( total no.of elements )*2(Size of one element)=12

Initialization and Storage Representation:

In C, two dimensional arrays can be initialized in different number of ways. Specification of no. Of columns in 2 dimensional array is mandatory while no of rows is optional.

Int a[2][3]={{1,3,0},   // Elements of 1st row

{-1,5,9}}; //  Elements of 2nd  row

 

OR

 

Int a[][3]={{1,3,0},    // Elements of 1st row

{-1,5,9}}; //  Elements of 2nd  row

 

OR

 

Int a[2][3]={1,3,0,-1,5,9};

 

Fig. 3 gives general storage representation of 2 dimensional array     

 

Col 0    Col 1                  Col n

 

Row 0             

 

a[0][0]

 

a[0][1]

 

 

  ---

a[0][n]

 

a[1][0]

 

a[1][1]

 

 

  ---

a[1][n]

 

-

-

 

-

-

 

a[m][0]

 

a[m][1]

 

 

a[m][n]

 

Row 1

 

-

-

Row m

Fig.3 General Storage Representation of 2 dimensional array.

 

Eg 4.  Int a[2][3]={1,3,0,-1,5,9}

 

1

 

3

0

-1

 

5

9

 

Row 0

Row 1

Col 0      col1      col2

Accessing Two-Dimensional Array Elements:

An element in 2-dimensional array is accessed by using the subscripts i.e. row index and column index of the array. For example:

Int val = A[1][2];

The above statement will access element from the 2nd row and third column of the array A i.e. element 9.

 

Memory allocation of 1D and 2D array

Sometimes the size of the array you declared may be insufficient. To solve this issue, you can allocate memory manually during run-time. This is known as dynamic memory allocation in C programming.

To allocate memory dynamically, library functions are malloc(), calloc(), realloc() and free() are used. These functions are defined in the <stdlib.h> header file.

C malloc()

The name "malloc" stands for memory allocation.

The malloc() function reserves a block of memory of the specified number of bytes. And, it returns a pointer of void which can be casted into pointers of any form.

Syntax of malloc()

Ptr = (castType*) malloc(size);

Example

Ptr = (float*) malloc(100 * sizeof(float));

The above statement allocates 400 bytes of memory. It's because the size of float is 4 bytes. And, the pointer ptr holds the address of the first byte in the allocated memory.

The expression results in a NULL pointer if the memory cannot be allocated.

C calloc()

The name "calloc" stands for contiguous allocation.

The malloc() function allocates memory and leaves the memory uninitialized. Whereas, the calloc() function allocates memory and initializes all bits to zero.

Syntax of calloc()

Ptr = (castType*)calloc(n, size);

Example:

Ptr = (float*) calloc(25, sizeof(float));

The above statement allocates contiguous space in memory for 25 elements of type float.

C free()

Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on their own. You must explicitly use free() to release the space.

Syntax of free()

Free(ptr);

This statement frees the space allocated in the memory pointed by ptr.

Example 1: malloc() and free()

// Program to calculate the sum of n numbers entered by the user

 

#include <stdio.h>

#include <stdlib.h>

 

Int main()

{

Int n, i, *ptr, sum = 0;

 

Printf("Enter number of elements: ");

Scanf("%d", &n);

 

Ptr = (int*) malloc(n * sizeof(int));

 

// if memory cannot be allocated

If(ptr == NULL)                    

{

Printf("Error! memory not allocated.");

Exit(0);

}

 

Printf("Enter elements: ");

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

{

Scanf("%d", ptr + i);

Sum += *(ptr + i);

}

 

Printf("Sum = %d", sum);

 

// deallocating the memory

Free(ptr);

 

Return 0;

}

Here, we have dynamically allocated the memory for n number of int.

Example 2: calloc() and free()

// Program to calculate the sum of n numbers entered by the user

 

#include <stdio.h>

#include <stdlib.h>

 

Int main()

{

Int n, i, *ptr, sum = 0;

Printf("Enter number of elements: ");

Scanf("%d", &n);

 

Ptr = (int*) calloc(n, sizeof(int));

If(ptr == NULL)

{

Printf("Error! memory not allocated.");

Exit(0);

}

 

Printf("Enter elements: ");

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

{

Scanf("%d", ptr + i);

Sum += *(ptr + i);

}

 

Printf("Sum = %d", sum);

Free(ptr);

Return 0;

}

C realloc()

If the dynamically allocated memory is insufficient or more than required, you can change the size of previously allocated memory using the realloc() function.

Syntax of realloc()

Ptr = realloc(ptr, x);

Here, ptr is reallocated with a new size x.

Example 3: realloc()

#include <stdio.h>

#include <stdlib.h>

 

Int main()

{

Int *ptr, i , n1, n2;

Printf("Enter size: ");

Scanf("%d", &n1);

 

Ptr = (int*) malloc(n1 * sizeof(int));

 

Printf("Addresses of previously allocated memory: ");

For(i = 0; i < n1; ++i)

Printf("%u\n",ptr + i);

 

Printf("\nEnter the new size: ");

Scanf("%d", &n2);

 

// rellocating the memory

Ptr = realloc(ptr, n2 * sizeof(int));

 

Printf("Addresses of newly allocated memory: ");

For(i = 0; i < n2; ++i)

Printf("%u\n", ptr + i);

 

Free(ptr);

 

Return 0;

}

When you run the program, the output will be:

Enter size: 2

Addresses of previously allocated memory:26855472

26855476

 

Enter the new size: 4

Addresses of newly allocated memory:26855472

26855476

26855480

26855484

Memory allocate a 2D array

A 2D array can be dynamically allocated in C using a single pointer. This means that a memory block of size row*column*dataTypeSize is allocated using malloc and pointer arithmetic can be used to access the matrix elements.

A program that demonstrates this is given as follows.

Example

#include <stdio.h>

#include <stdlib.h>

Int main() {

Int row = 2, col = 3;

Int *arr = (int *)malloc(row * col * sizeof(int));

Int i, j;

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

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

*(arr + i*col + j) = i + j;   

Printf("The matrix elements are:\n");

For (i = 0; i < row; i++) {

For (j = 0; j < col; j++) {

Printf("%d ", *(arr + i*col + j));

}

Printf("\n");

}

Free(arr);

Return 0;

}

The output of the above program is as follows.

The matrix elements are:

0 1 2

1 2 3

Now let us understand the above program.

The 2-D array arr is dynamically allocated using malloc. Then the 2-D array is initialized using a nested for loop and pointer arithmetic. The code snippet that shows this is as follows.

Int row = 2, col = 3;

Int *arr = (int *)malloc(row * col * sizeof(int));

Int i, j;

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

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

*(arr + i*col + j) = i + j;

Then the values of the 2-D array are displayed. Finally the dynamically allocated memory is freed using free. The code snippet that shows this is as follows.

Printf("The matrix elements are:\n");

For (i = 0; i < row; i++) {

For (j = 0; j < col; j++) {

Printf("%d ", *(arr + i*col + j));

}

Printf("\n");

}

Free(arr);

 


Index
Notes
Highlighted
Underlined
:
Browse by Topics
:
Notes
Highlighted
Underlined