C lecture 3.1
C lecture 3.1
Necessity of array: Consider a scenario where you need to find out the average of 100 integer numbers entered by
user. In C, you have two ways to do this: 1) Define 100 variables with int data type and then perform 100 scanf()
operations to store the entered values in the variables and then at last calculate the average of them. 2) Have a single
integer array to store all the values, loop the array to store all the entered values in array and later calculate the
average.
Obviously the second solution is better, it is convenient to store same data types in one single variable and later access
them using array index.
Example: int student[10]; represents the collection of 10 students, while the complete set of values is referred to as
an array, the individual values are called elements. Arrays can be of any variable type. A particular value is indicated
by writing a number called index number or subscript in brackets after the array name.
Declaration of array:
int num[35]; /* An integer array of 35 elements */
char ch[10]; /* An array of characters for 10 elements */
Similarly an array can be of any data type such as double, float, short etc.
We can use array subscript (or index) to access any element stored in array. Subscript starts with 0, which
means arr[0] represents the first element in the array . In general student[n-1] can be used to access nth element of an
array. where n is any integer number.
1D Array: a list of items can be given one variable name using only one subscript and such a variable is called ingle
subscripted variable or one-dimensional array. To calculate the average of n numbers, 1D array is used, its subscript
can begin with number 0.
Memory allocation: let, 5 numbers need to be represented:{35,10,24,60,7}, in memory their location be like:
35 10 24 60 7
For 2D array, we must always specify the second dimension even if we are specifying elements during the declaration.
/* Valid declaration*/
int abc[2][2] = {1, 2, 3 ,4 }
/* Valid declaration*/
int abc[][2] = {1, 2, 3 ,4 }
/* Invalid declaration – you must specify second dimension*/
int abc[][] = {1, 2, 3 ,4 }
/* Invalid because of the same reason mentioned above*
/ int abc[2][] = {1, 2, 3 ,4 }
Example: 2D array memory representation:
#include<stdio.h>
int main()
{
/* 2D array declaration*/
int abc[5][4];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<5; i++)
{
for(j=0;j<4;j++)
{
printf("Enter value for abc[%d][%d]:", i, j);
scanf("%d", &abc[i][j]);
}
}
return 0;
}
Multidimensional array: C programming language allows multidimensional arrays. Here is the general form of a
multidimensional array declaration −
type name[size1][size2]...[sizeN];
For example: int threedim[5][10][4];
Function Purpose