Introduction To Arrays

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Introduction To Arrays:

In C programming, one of the frequently problem is to handle similar types of data. For example: if the
user wants to store marks of 500 students, this can be done by creating 500 variables individually but,
this is rather tedious and impracticable. These types of problem can be handled in C programming using
arrays.

An array in C Programing can be defined as number of memory locations, each of which can store the
same data type and which can be references through the same variable name. It is a collective name
given to a group of similar quantities. These similar quantities could be marks of 500 students, number
of chairs in university, salaries of 300 employees or ages of 250 students. Thus we can say array is a
sequence of data item of homogeneous values (same type). These values could be all integers, floats or
characters etc.

We have two types of arrays:

1. One-dimensional arrays.
2. Multidimensional arrays.

One Dimensional Arrays:


A one-dimensional array is a structured collection of components (often called array elements) that can
be accessed individually by specifying the position of a component with a single index value. Arrays must
be declared before they can be used in the program. Here is the declaration syntax of one dimensional
array:

data_type array_name[array_size];

Here “data_type” is the type of the array we want to define, “array_name” is the name given to the
array and “array_size” is the size of the array that we want to assign to the array. The array size is always
mentioned inside the “[]”.

For example:
Int age[5];

int age [5];

Here int is Age is the [5] is the size of


the data name of the the array
type array
The following will be the result of the above declarations:

age[0] age[1] age[2] age[3] age[4]

Initializing Arrays
Initializing of array is very simple in c programming. The initializing values are enclosed within the curly
braces in the declaration and placed following an equal sign after the array name. Here is an example
which declares and initializes an array of five elements of type int. Array can also be initialized after
declaration. Look at the following code, which demonstrate the declaration and initialization of an array.

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

It is not necessary to define the size of arrays during initialization e.g.

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

In this case, the compiler determines the size of array by calculating the number of elements of an array.

age[0] age[1] age[2] age[3] age[4]


2 3 4 5 6

Accessing array elements


In C programming, arrays can be accessed and treated like variables in C.

For example:

 scanf("%d",&age[2]);
//statement to insert value in the third element of array age[]

 printf("%d",age[2]);
//statement to print third element of an array.

Arrays can be accessed and updated using its index.An array of n elements, has indices ranging from 0 to
n-1. An element can be updated simply by assigning

A[i] = x;
A great care must be taken in dealing with arrays. Unlike in Java, where array index out of bounds
exception is thrown when indices go out of the 0..n-1 range, C arrays may not display any warnings if out
of bounds indices are accessed. Instead,compiler may access the elements out of bounds, thus leading
to critical run time errors.
Example of array in C programming

/* C program to find the sum marks of n students using arrays */

#include <stdio.h>

int main(){

int i,n;
int marks[n];
int sum=0;

printf("Enter number of students: ");


scanf("%d",&n);

for(i=0;i<n;i++){
printf("Enter marks of student%d: ",i+1);
scanf("%d",&marks[i]); //saving the marks in array
sum+=marks[i];
}

printf("Sum of marks = %d",sum);

return 0;

Output :

Enter number of students: (input by user)3


Enter marks of student1: (input by user) 10
Enter marks of student2: (input by user) 29
Enter marks of student3: (input by user) 11

Sum of marks = 50

Important thing to remember in C arrays


Suppose, you declared the array of 10 students. For example: students[10]. You can use array members
from student[0] to student[9]. But, what if you want to use element student[10], student[100] etc. In
this case the compiler may not show error using these elements but, may cause fatal error during
program execution.
Multidimensional Arrays:
C programming language allows the user to create arrays of arrays known as multidimensional arrays.
To access a particular element from the array we have to use two subscripts one for row number and
other for column number. The notation is of the form array [i] [j] where i stands for row subscripts and j
stands for column subscripts. The array holds i*j elements. Suppose there is a multidimensional array
array[i][j][k][m]. Then this array can hold i*j*k*m numbers of data. In the same way, the array of any
dimension can be initialized in C programming. For example :

int smarks[3][4];

Here, smarks is an array of two dimension, which is an example of multidimensional array. This array has
3 rows and 4columns. For better understanding of multidimensional arrays, array elements of above
example can be as below:

Col 1 Col 2 Col 3 Col 4


Row 1 smakrs[0][0] smarks[0][1] smarks[0][2] smarks[0][3]

Row 2 smarks[1][0] smarks[1][1] smarks[1][2] smarks[1][3]


Row 3 smarks[2][0] smarks[2][1] smarks[2][2] smarks[2][3]

Make sure that you remember to put each subscript in its own, correct pair of brackets. All three
examples below are wrong.

int a2[5, 7]; /* XXX WRONG */

a2[i, j] = 0; /* XXX WRONG */

a2[j][i] = 0; /* XXX WRONG */

would do anything remotely like what you wanted

Initialization of Multidimensional Arrays


In C, multidimensional arrays can be initialized in different number of ways.

int smarks[2][3]={{1,2,3}, {-1,-2,-3}};


OR
int smarks[][3]={{1,2,3}, {-1,-2,-3}};
OR
int smarks[2][3]={1,2,3,-1,-2,-3};
Coding example of Multidimensional Array:

This program asks user to enter the size of the matrix (rows and column) then, it asks the user to enter
the elements of two matrices and finally it adds two matrix and displays the result.

Source Code to Add Two Matrix in C programming


#include <stdio.h>

int main(){
int r,c;
int a[r][c];
int b[r][c];
int sum[r][c;

printf("Enter number of rows (between 1 and 100): ");


scanf("%d",&r);

printf("Enter number of columns (between 1 and 100): ");


scanf("%d",&c);

printf("\nEnter elements of 1st matrix:\n");

/* Storing elements of first matrix entered by user. */

for(int i=0;i<r;++i){
for(int j=0;j<c;++j){
printf("Enter element a%d%d: ",i+1,j+1);
scanf("%d",&a[i][j]);
}
}

/* Storing elements of second matrix entered by user. */

printf("Enter elements of 2nd matrix:\n");


for(int i=0;i<r;++i){
for(int j=0;j<c;++j){
printf("Enter element a%d%d: ",i+1,j+1);
scanf("%d",&b[i][j]);
}
}

/*Adding Two matrices */

for(int i=0;i<r;++i)
for(int j=0;j<c;++j)
sum[i][j]=a[i][j]+b[i][j];

/* Displaying the resultant sum matrix. */


printf("\nSum of two matrix is: \n\n");
for(int i=0;i<r;++i){
for(int j=0;j<c;++j){
printf("%d ",sum[i][j]);
if(j==c-1)
printf("\n\n");
}

return 0;

Program Output:
Enter number of rows (between 1 and 100): 3
Enter number of rows (between 1 and 100): 2

Enter elements of 1st matrix:


Enter element a11: 4
Enter element a12: -4
Enter element a21: 8
Enter element a22: 5
Enter element a31: 1
Enter element a32: 0
Enter elements of 2nd matrix:
Enter element a11: 4
Enter element a12: -7
Enter element a21: 9
Enter element a22: 1
Enter element a31: 4
Enter element a32: 5

Sum of two matrix is:

8 -11

17 6

5 5
Dynamic Arrays and Resizing
Arrays by definition are static structures, meaning that size cannot be changed during run time. When
an array is defined as

int A[n];

then A is considered a static array and memory is allocated from the run time stack for A. When A goes
out of scope, the memory is deallocated and A no longer can be referenced. C allows dynamic
declaration of an array as follows:

int* A = (int*)malloc(n* sizeof(int))

The above code declares a memory block of size n*sizeof(int) that can be accessed using the pointer A.
For example, A can be initialized as follows:

int i;
for (i=0; i<n; i++)
A[i] = 0;

Note that although A was declared as a pointer, A can be treated as an array. The difference between

int A[10] and int* A = malloc(10*sizeof(int)) is that latter is assigned memory in the dynamic heap (and

hence must be managed by the programmer) and former is assigned memory from the run time stack
(and hence managed by the compiler). Static arrays are used when we know the amount of bytes in
array at compile time while the dynamic array is used where we come to know about the size on run
time. Arrays can also be initialized using the calloc() functions instead of the the malloc(). Calloc function
is used to reserve space for dynamic arrays. Has the following form.

array =(cast-type*)calloc(n,element-size);
Number of elements in the first argument specifies the size in bytes of one element to the second
argument. A successful partitioning, that address is returned, NULL is returned on failure. For example,
an int array of 10 elements can be allocated as follows.

int * array = (int *) calloc (10, sizeof (int));

Note that this function can also malloc, written as follows.

int * array = (int *) malloc (sizeof (int) * 10)

Arrays and Functions


In C, Arrays can be passed to functions using the array name. Array name is a const pointer to the array.
both one-dimensional and multi-dimensional array can be passed to function as argument. Individual
element is passed to function using pass by value. Original Array elements remain unchanged, as the
actual element is never passed to function. Thus function body cannot modify original value in this case.
If we have declared an array ‘array [5]‘ then instead of passing individual elements, a for loop is useful in
this case to pass all 5 elements of the array.

Passing One-dimensional Array In Function

C program to pass a single element of an array to function


#include <stdio.h>
void display(int a)
{
printf("%d",a);
}
int main(){
int c[]={2,3,4};
display(c[2]); //Passing array element c[2] only.
return 0;
}

Output

4
Single element of an array can be passed in similar manner as passing variable to a function.

Passing entire one-dimensional array to a function


While passing arrays to the argument, the name of the array is passed as an argument(,i.e, starting
address of memory area is passed as argument).

C program to pass an array containing age of person to a function. This function will return average
age and display the average age in main function.

#include <stdio.h>
float average(float a[]);
int main(){
float avg, c[]={23.4, 55, 22.6, 3, 40.5, 18};
avg=average(c); /* Only name of array is passed as argument. */
printf("Average age=%.2f",avg);
return 0;
}
float average(float a[]){
int i;
float avg, sum=0.0;
for(i=0;i<6;++i){
sum+=a[i];
}
avg =(sum/6);
return avg;
}

Output
Average age=27.08

Passing Multi-dimensional Arrays to Function


To pass two-dimensional array to a function as an argument, starting address of memory area reserved
is passed as in one dimensional array

Example to pass two-dimensional arrays to function


#include
void Function(int c[2][2]);
int main(){
int c[2][2],i,j;
printf("Enter 4 numbers:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
scanf("%d",&c[i][j]);
}
Function(c); /* passing multi-dimensional array to function */
return 0;
}
void Function(int c[2][2]){
/* Instead to above line, void Function(int c[][2]){ is also valid */
int i,j;
printf("Displaying:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
printf("%d\n",c[i][j]);

Output
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5

You might also like