Lecture 7 - Arrays (1) : PGT 106: C Programming 1
Lecture 7 - Arrays (1) : PGT 106: C Programming 1
1. Introduction
2. Arrays of Data
3. Array Declaration
4. Array Initialization
5. Operations on Array
6. Multidimensional Arrays
7. Index out of bound
Sa m e
da ta
Sa m e
type
na m e
n By using array,
int aiNum[5];
aiNum n 5 components or
elements
5 aiNum[0]
10 aiNum[1] n Elements are referred to
index.
15 aiNum[2]
20 aiNum[3] n Element aiNum[2] has
index 2 and value 15.
25 aiNum[4]
n Format:
n data_type array_name [int value];
// multiple instance
int iValue1, iValue2, iValue3, printf (“Enter fourth value: “);
iValue4, iValue 5; scanf(“%d”, &iValue4)
printf (“Enter first value: “); printf (“Enter fifth value: “);
scanf (“%d”, &iValue1); scanf(“%d”, &iValue5)
• Initializers:
– If not enough initializers, rightmost element becomes 0
int aiN[ 7 ] = { 1, 2, 3, 4, 5 }; => aiN[5] = aiN[6] = 0
– All elements = 0
int aiN[ 5 ] = { 0 } ;
▪ If size is omitted, initializers determine the size
int aiN[ ] = { 1, 2, 3, 4, 5 };
5 initializers, therefore 5 element array
for (iLoop=0;iLoop<10;iLoop++)
{ Using a loop to fill all the
adY[iLoop]= iLoop*100.0; elements of the adY[] array.
printf(“adY[%1d]=%.2lf\n", iLoop, adY[i]);
}
return 0;
}
adY[0]=0.00
adY[1]=100.00
adY[2]=200.00
adY[3]=300.00
adY[4]=400.00
adY[5]=500.00
adY[6]=600.00
adY[7]=700.00
adY[8]=800.00
adY[9]=900.00
void main()
{
int iLoop, iTotal = 0; // variable declaration
int aiY[n]={9,6,20,5,12}; // array declaration and
// initialization
for (iLoop=0;iLoop<n;iLoop++)
iTotal = iTotal + aiY[i];
printf ("\nTotal = %d\n”, iTotal);
}
• Printing an array
for (iIndex = 0; iIndex < 10; iIndex++)
printf (“%d ”, aiSale[iIndex]);
int aiValue[4][2];
index aiValue
0
aiValue[2][1]=5; Row 0
1
Column
2
0 1 Row 1
3
0
4
1
Row 5 5
2 5 6
3
7
– array_type
int aiB[2][3] = {51,
array_name
52, 53, 54, 55, 56};
Array dimension = 2
two rows
three columns first row second row
initial values initial values