PPS Ch-7.Array
PPS Ch-7.Array
ARRAY
❖ Array is a data structure which can represent a collection of data items which
have the same data type (float/int/char)
Array
● All the data items constituting the group share the same name.
int x[10];
X is a 10-element one
dimensional array
Declaring Arrays
Like variables, the arrays that are used in a program must
be declared before they are used.
● If we are not sure of the exact size of the array, we can define an array of a
large size.
int marks[50];
Accessing Array Elements
● A particular element of the array can be accessed by specifying
two things:
● Examples:
○ int marks[5] = {72, 83, 65, 80, 76};
○ char name[4] = {‘A’, ‘m’, ‘i’, ‘t’};
min = 99999;
for (i=0; i<10; i++)
{
if (a[i] < min)
min = a[i];
}
printf (“\n Minimum is %d”, min);
}
How to read the elements of an array?
By reading
them one
element at a
time The elements can
• for (j=0; j<25; The ampersand be entered all in
j++) (&) is necessary. one line or in
• scanf (“%f”, different lines.
&a[j]);
How to print the elements of an array?
● By printing them one element at a time.
for (j=0; j<25; j++)
printf (“\n %f”, a[j]);
○ The elements are printed one per line.
printf (“\n”);
for (j=0; j<25; j++)
printf (“ %f”, a[j]);
○ The elements are printed all in one line (starting with a new line).
Two Dimensional Arrays
● We have seen that an array variable can store a list of values.
● Many applications require us to store a table of values.
Student 1 75 82 90 65 76
Student 2 68 75 80 70 72
Student 3 88 74 85 76 80
Student 4 50 65 68 40 70
Contd.
● The table contains a total of 20 values, five in each line.
○ The table can be regarded as a matrix consisting of four rows and five columns.
● Examples:
int marks[4][5];
float sales[12][25];
double matrix[100][100];
Accessing Elements of a 2-D Array
● Similar to that for 1-D array, but use two indices.
○ First indicates row, second indicates column.
○ Both the indices should be expressions which evaluate to integer
values.
● Examples:
x[m][n] = 0;
c[i][k] += a[i][j] * b[j][k];
a = sqrt (a[j*3][k]);
How to read the elements of a 2-D array?
● By reading them one element at a time