Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
1
ARRAYS
An array is a collection of elements
Of the same type that are referenced by a common name.
Compared to the basic data type (int, float & char) it
is an aggregate or derived data type.
All the elements of an array occupy a set of contiguous
memory locations.
2
We have a list of 1000 students' marks of an
integer type. Using the basic data type (int):
intstudMark0,studMark1,studMark2,...,studMark999;
ARRAYS
Can you imagine how long we have to write the
declaration part (using normal variable)?
intmain(void)
{
intstudMark1,studMark2,studMark3,
studMark4,,,studMark998,stuMark999,
studMark1000;
3
return0;
}
ARRAYS
By using an array,
int studMark[1000];
This will reserve 1000 contiguous memory locations for storing the
students marks as shown below:
4
1D Array
5
Char ARRAYS
Example: an array of 30 characters:
charcName[30];
6
ARRAYS
More examples:
intxNum[20],yNum[50];
floatfPrice[10],fYield;
charletters[70];
7
ARRAY Initialization
An array may be initialized at the time of declaration.
Initialization of an array may take the following form,
typearray_name[size]={a_list_of_value};
Example:
intidNum[7]={1,2,3,4,5,6,7};
charchVowel[6]={'a','e','i','o','u','\0'};
chararray_name[size]="string_laterals";
For example, the array chVowel in the previous example could have been
written more compactly as follows,
charchName[]="Mr.Dracula";
C compiler automatically creates an array which is big enough to hold all the
initializer.
Example program
#include <stdio.h>
int main(){
int i, sum;
float avg;
sum = 0;
for (i = 0; i < 5; i++)
sum = sum + i;
12
2D ARRAYS
A 2D array has two subscripts/indexes. First subscript refers to the
row, and the second, to the column.
data_typename[1stdimensionsize][2nddimensionsize];
Examples,
intnum[3][4];
floatmatrixNum[20][25];
The first line declares numas an integer array with 3 rows and 4
columns.
13
Second line declares a matrixNum as a floating-point array with 20
rows and 25 columns.
2D ARRAYS example
Consider a 2D char array:
charName[6][10]={"Mr.Bean","Mr.Bush","Nicole",
"Kidman","Arnold","Jodie"};
14
Size of ARRAYS
For Name[6][10], the array size is 6 x 10 = 60
array_name[x][y];
ThreeDimArray[2][4][7]= 2 x 4 x 7 = 56.
And if you want to illustrate the 3D array, it could be a cube with wide, long
15 and height dimensions.
Thank you
Let us do some programming
16