Sie sind auf Seite 1von 55

Arrays

(Part I)

Dr. Ku Nurul Fazira bt. Ku Azir


fazira@unimap.edu.my

1
1. Introduction to Array
2. Arrays of Data
3. Array Declaration
4. Array Initialization
5. Operations on Array
6. Multidimensional Arrays
7. Index out of bound
8. Passing Arrays to Function
9. Displaying Array in a Function
10. How Arrays are passed in a function call

2
 The variables that we have used so far have all common
characteristics:
 Each variable could only store a single value at a time.

 Example:
int iCount=15;
int iCount 15
double dAverage=3.2;
double dAverage 3.2
char cChoice=„y‟;
char cChoice y

 An array is a collection of a fixed number of components wherein


all of the components are of the same type

3
 Example: Suppose that there is a list of five integers:
5, 10, 15, 20, and 25

 Previously we would declare five variables:

int iNum1,iNum2,iNum3,iNum4,iNum5; //declaration

//assign numbers to every variable


iNum1=5;
iNum2=10;
iNum3=15;
iNum4=20;
iNum5=25;

4
By using array, since they are all of the same data type, we
could declare them as an array:
Declaration int aiNum[5]; aiNum

Assign 5 to aiNum[0]=5; aiNum[0] 5


element with Element
aiNum[1]=10; aiNum[1] 10 aiNum[1] has
index
aiNum[2]=15; 15 index 1 and value 10
number 0 aiNum[2]
aiNum[3]=20; aiNum[3] 20
aiNum[4]=25; aiNum[4] 25

 int is the data type of the array


 5 in squared bracket is the number of components/elements in the array
 Elements are referred to an index number
 Index number starts with 0
5
 Engineering applications usually involve large chunk of
data (of common type)
 Arrays provide easy and efficient concept for data
storage or management
 Arrays are usually processed through loops
 Arrays are accessed by indicating an index or address

6
 Arrays can assume any type (including the primitive data
types)
int, char, double, float, etc.

 Like any other instances, arrays must be declared before use.


int aiNum[5];
float afNum[7];
double adNum[8];
char acName[10];

7
int aiNum[8];
 Arrays are allocated bulk index aiNum
memory aiNum[0]=23; 0 23
aiNum[1]=56; 1 56
 Single reference used for 100
aiNum[2]=100; 2
multiple locations aiNum[3]=0; 3 0

 Items are accessed based on aiNum[4]=12; 4 12

index (address) with reference aiNum[5]=234; 5 234

aiNum[6]=666; 6 666
to first item
aiNum[7]=4; 7 4

8
 Arrays can be initialized directly, but assignments are done using loops
 Like any other simple variable, arrays can also be initialized while they are being
declared.
 Example:

float aiNum[5];//declaration
//initialization
aiNum[0]=5, aiNum[1]=10, aiNum[2]=15, aiNum[3]=20,
aiNum[4]=25;

OR

//initialization during declaration


float aiNum[5] = {5,10,15,20,25};
9
 Initializers:
 If not enough initializes, rightmost element becomes 0
int aiNum[7] = {5, 10, 15, 20, 25};
=> aiNum[5] = aiNum[6] = 0

 All elements = 0
int aiNum[7] = {0} ;

 If size is omitted, initializers determine the size


int aiNum[] = {5, 10, 15, 20, 25};
 5 initializers, therefore 5 element array
 Size of the array is determined by the number of initial values in the braces.

NOTE: When declaring and initializing arrays, it is not necessary to specify the size
10 of the array.
// multiple instance // array
int iValue1, iValue2, iValue3; int aiValue[3];

printf (“Enter value 1: “); printf (“Enter value 1: “);


scanf (“%d”, &iValue1); scanf (“%d”, &aiValue[0]);

printf(“Enter value 2: “); printf(“Enter value 2: “);


scanf(“%d”, &iValue2); scanf(“%d”, &aiValue[1]);

printf (“Enter value 3: “); printf (“Enter value 3: “);


scanf(“%d”, &iValue3); scanf(“%d”, &aiValue[2]);

// process or display // process or display

11
// multiple instance // array
int iValue1, iValue2, iValue3; int aiValue[3];
int i; Using Loops

printf (“Enter value 1: “); for(i=1;i<=3;i++)


scanf (“%d”, &iValue1); {
printf (“Enter value %d: “,i+1);
printf(“Enter value 2: “); scanf (“%d”, &aiValue[i]);
scanf(“%d”, &iValue2); }

printf (“Enter value 3: “);


scanf(“%d”, &iValue3); // process or display

// process or display

12
 Storing/Reading data in an array

int aiSale[5];
int iIndex=0;
for (iIndex = 0; iIndex < 5; iIndex++)
scanf (“%d”, &aiSale[iIndex]);
aiSale
Input number:
aiSale[0] 23
aiSale[1] 11
aiSale[2] 55
aiSale[3] 47
aiSale[4] 39
13
 Printing an array
int aiSale[5];
int iIndex=0;
for (iIndex = 0; iIndex < 5; iIndex++)
scanf (“%d”, &aiSale[iIndex]);
for (iIndex = 0; iIndex < 5; iIndex++)
printf (“%d”, aiSale[iIndex]);
aiSale
Output number:
aiSale[0] 23 23
aiSale[1] 11 11
aiSale[2] 55 55
aiSale[3] 47 47
14 aiSale[4] 39 39
Initializes the first 2 elements of the aiA[]array.
#include <stdio.h> All the other elements are then automatically set to zero
int main()
Because no array size is given (the
{ brackets are empty) and three values are
int aiA[3]= {11,22}, aiB[]={44, 55, 66}; given in braces, the array is automatically
declared to have a size of 3 with the value
shown being the initial element values.

printf(“aiA[0]=%2d, aiA[1]=%2d, aiA[2]=%2d \n


“aiB[0]=%2d, aiB[1]=%2d, aiB[2]=%2d \n\n",
aiA[0],aiA[1],aiA[2],aiB[0],aiB[1],aiB[2]);

return 0;
}

15
Initializes the first 2 elements of the
#include <stdio.h> aiA[]array.
int main() All the other elements are then
automatically set to zero
{
int aiA[3]= {11,22}, aiB[]={44, 55, 66};
Because no array size is
given (the brackets are
empty) and three values
are given in braces, the
printf(“aiA[0]=%2d, aiA[1]=%2d, aiA[2]=%2d \n array is automatically
“aiB[0]=%2d, aiB[1]=%2d, aiB[2]=%2d \n\n", declared to have a size
of 3 with the value
aiA[0],aiA[1],aiA[2],aiB[0],aiB[1],aiB[2]);
shown being the initial
element values.

return 0;
} Output:

aiA[0]=11, aiA[1]=22, aiA[2]= 0


aiB[0]=44, aiB[1]=55, aiB[2]=66
16
#include <stdio.h>

int main()
{
int listA[2],listB[5],iLoop;

printf("Please enter two integers\n");


scanf("%d %d",&listA[0], &listA[1]);
printf(“\n listA[0] = %d listA[1] = %d\n\n", listA[0],
listA[1]);

printf("Please enter five integers\n");

for(iLoop=0;iLoop<5;iLoop++)
scanf("%d",&listB[iLoop]);

for(iLoop=0;iLoop<5;iLoop++)
printf(“listB[iLoop]=%d ",listB[iLoop]);
printf(”\n”);
17
#include <stdio.h>

int main()
{
int listA[2],listB[5],iLoop;

printf("Please enter two integers\n");


scanf("%d %d",&listA[0], &listA[1]);
printf(“\n listA[0] = %d listA[1] = %d\n\n", listA[0],
listA[1]);
Output:
printf("Please enter five integers\n"); Please enter two integer
1 2
for(iLoop=0;iLoop<5;iLoop++)
scanf("%d",&listB[iLoop]);
listA[0] = 1 listA[1] = 2
Please enter five integers
for(iLoop=0;iLoop<5;iLoop++) 34567
listB[0]= 3 listB[1]= 4 listB[2]= 5
printf(“listB[iLoop]=%d ",listB[iLoop]);
printf(”\n”); listB[3]= 6 listB[4]=7
18
 Operations on arrays are similar to basic variables.
 Must include index number of the element during operations to
specify which element to be used
 Example: Index number

 iSum = aiNum[0] + aiNum[1] + aiNum[2];


 iMultiply = 3 * aiNum[1];
 iRemainder = aiNum[3] % 3;
 iTotal = aiNum[1] * aiNum[2];

19
#include <stdio.h>
#define n 5

int main()
All elements are set to 0.
{

int list[n]={0},iLoop; Using a loop to fill all the


elements of the list[] array.

for (iLoop=0;iLoop<5;iLoop++)
{
list[iLoop]= iLoop*100.0;
printf(“list[%d]=%d\n", iLoop, list[iLoop]);
}
return 0;
}

20
20
#include <stdio.h>
#define n 5

int main()
All elements are set to 0.
{

int list[n]={0},iLoop; Using a loop to fill all the


elements of the list[] array.

for (iLoop=0;iLoop<5;iLoop++)
{
list[iLoop]= iLoop*100.0;
Output:
printf(“list[%d]=%d\n", iLoop, list[iLoop]);
}
list[0]=0
return 0; list[1]=100
} list[2]=200
list[3]=300
list[4]=400

21
21
#include<stdio.h>
#define n 10 //define number of n in the array

void main()
{  the array size n is
int iLoop, iTotal = 0; //variable declaration
declared in the define
statement.
int aiY[n]={9,6,20,5,12}; //array declaration &
//initialization

for (iLoop=0;iLoop<n;iLoop++)
iTotal = iTotal + aiY[iLoop];

printf ("\nTotal = %d\n”, iTotal);


}

22
#include<stdio.h>
#define n 10 //define number of n in the array

void main()
{  program declares and
int iLoop, iTotal = 0; //variable
initializes declaration
the array aiY
int aiY[n]={9,6,20,5,12}; //array declaration &
//initialization

for (iLoop=0;iLoop<n;iLoop++)
iTotal = iTotal + aiY[iLoop];

printf ("\nTotal = %d\n”, iTotal);


}

23
#include<stdio.h>
#define n 10 //define number of n in the array

void main()
{
int iLoop, iTotal = 0;
 For each loop
int aiY[n]={9,6,20,5,12}; iteration, the value
accessed id is added
to the variable iTotal
for (iLoop=0;iLoop<n;iLoop++) which is finally
iTotal = iTotal + aiY[iLoop]; displayed.

printf ("\nTotal = %d\n”, iTotal);


}

24
 defined constants, #define
 used to ease any future amendments of the codes
 Eg: if the array is to be widen to an n of 10 instead of 5, it would be
adequate by modifying the line:
#define n 5  #define n 10
there is no need to make any other changes to the
program, thus making the life of programmer easier

25
 Two (or more) arrays are called parallel if their corresponding
components hold related information
Example 1:
int aiStudentId[5]= {14100701, 14100702, 14100703,
14100704, 14100705};
char acStudentGrade[5]={„A‟,‟B‟,‟C‟,‟A‟,‟B‟};

aiStudentId Corresponding acStudentGrade


information
aiStudentId[0] 14100701 acStudentGrade[0] A
aiStudentId[1 14100702 acStudentGrade[1 B
] ] C
aiStudentld[2 1410073 acStudentGrade[2
] 1400074 ]
acStudentGrade[3] A
aiStudentId[3]
aiStudentId[4 1400075 acStudentGrade[4 B
] ]
26
 Two (or more) arrays are called parallel if their
corresponding components hold related information

Example 2:
float afWeightKg[5]= {1.5,2.5,3.5,4.5,5.5};
float afWeightPound[5]={3.31,5.51,7.71,9.92,12.13};

afWeightKg Corresponding afWeightPound


information
afWeightKg[0] 1.5 afWeightPound[0] 3.31
afWeightKg[1 2.5 afWeightPound[1] 5.51
] 3.5 7.71
afWeightKg[2 afWeightPound[2]
]
afWeightKg[3] 4.5 afWeightPound[3] 9.92
afWeightKg[4 5.5 afWeightPound[4] 12.13
]
27
#include<stdio.h>
#define n 5 //define number of n in the array

void main()
{
int i;
float afWeightKg[n]={1.5,2.5,3.5,4.5,5.5};
float afWeightPound[n]={0};
float sumPound=0,sumKg=0; Weight in kg from ith element of array afWeight is
converted to pound and assigned to ith element of
array afWeightPound
for (i=0;i<n;i++)
{
afWeight[i] = afWeightKg[i] * 2.204; Weight in kg from ith element of array afWeight
sumKg=sumKg+afWeightKg[i]; is summed and assign to sumKg
sumPound=sumPound+afWeightPound[i];
} Weight in pound from ith element of array afPound is
summed and assign to sumPound

for (i=0;i<n;i++)
printf(“afWeightPound[i]=%f\n”,afWeightPound[i]);

printf ("\nSum Kg = %.2f\n Sum Pound = %.2f\n”,sumKg, sumPound);

28}
 Arrays can have multiple dimensions
 Most used is the 2-dimensional array (for matrix
implementation)
 Actual implementation is a single array (segmented)
 Nested loop structure usually used to access items

29
int aiValue[4][2];//declaration

aiValue[2][1]=5;

Column
0 1
0 aiValue[0][0] aiValue[0][1]
1 aiValue[1][0] aiValue[1][1]
Row
2 aiValue[2][0] aiValue[2][1]
3 aiValue[3][0] aiValue[3][1]

30
int aiValue[4][2];

aiValue[2][1]=5;//assignment of value

Column
0 1
0 aiValue[0][0] aiValue[0][1]
1 aiValue[1][0] aiValue[1][1]
Row
2 aiValue[2][0] 5
3 aiValue[3][0] aiValue[3][1]

31
 A collection of the same type of data stored in contiguous
and increasing memory locations.
 Declaration of multi-dimensional array:
array_type array_name array dimension =
2

int aiNum1[2][3] = {51, 52, 53, 54, 55, 56};

two rows
three columns first row second row
initial values initial values

32
 Multi-dimensional array can be initialized directly in the
declaration statement.
 For example:
 int aiNum2[2][3] = {51,52,53,54,55,56};
which initializes the elements to be
aiNum2[0][0]=51 aiNum2[0][1]=52 aiNum2[0][2]=53
aiNum2[1][0]=54 aiNum2[1][1]=55 aiNum2[1][2]=56
• note that C begins its subscripts at 0.
• The rightmost subscript is incremented first.

33
 can use braces ({ }) to separate rows in 2-dimensional arrays
 For example:

3 columns
int aiNum[4][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}, 4 rows
rows
{10,11,12}};
columns

34
 int aiNum [4][3] = { {1, 2},
{4, 5, 6},
{7},
{10,11,12} };

initializes aiNum[0][2], aiNum[2][1] and aiNum[2][2] to be 0

 int aiNum[ ][3] = {{1, 2, 3},


{4, 5, 6},
{7, 8, 9},
{10,11,12}};
implicitly declares the number of rows to be 4

35
 Arrays enable better and easier data management system
 Closely related to loops
 Indexing is zero-based (0 to n-1 for an array with n
locations)
 Multi-dimensional arrays require nested loop structure
(e.g. 2-dimensional array)

36
 ‘Out of bounds’ is when (index < 0) or (index > arraySize - 1)
 It is a run-time error, happens when an index is outside the valid boundaries of
the array
aiNum
Example: X
aiNum[0] 3
int aiNum[5];
aiNum[-1]=1;//out of bound aiNum[1] 6
aiNum[1]=3; //ok aiNum[2]
aiNum[2]=6; //ok aiNum[3]
aiNum[5]=4;//out of bound aiNum[4]
X

 In C, no guard against this problem


 Without checking whether index value is within range or not can result in
37 accessing data of wrong memory location
 Use defined loops

for (iLoop=0; iLoop<10; iLoop++)


aiList[iLoop] = 0;

38
#include<stdio.h>

void fnInitialize(int []);

int main()
{
int aiListX[5];//declaration of array

fnInitialize(aiListX);// passing array to function fnInitialize

return 0;

void fnInitialize(int aiList[])


{
int i;

for(i=0; i<5; i++)


aiList[i] = 0; //initialize all elements to 0
}

39  Initializes int array of size 5 to 0.


 If size changes (lets say 10 or 20), need to write another function.  not practical and inflexible.
 Therefore, introduce another variable, iSize.

#include<stdio.h>

void fnInitialize(int [],int);

int main()
{
int aiListX[10];
int iSize=10;
fnInitialize(aiListX,iSize);

return 0;
}

void fnInitialize(int aiList[], int iSize)


{
int i;
40 for(i=0; i<iSize; i++)
aiList[iCount] = 0;
 Prevent the function from changing the values in array.
 Use word const in declaration.
 Function can modify array aiX but not array aiY
#include<stdio.h>

void fnInitialize(int [],const int [],int, int);

int main()
{
int aiListX[10];
const int aiListY[5];

fnInitialize(aiListX,aiListY,10,5);

return 0;
}

void fnInitialize(int aiX[], const int aiY[],int sizeX, int sizeY)


{
int i;

for(i=0; i<sizeX; i++)


41 aiX[i] = 0; //initialize elements in aiX with 0
#include<stdio.h>
void fnInitialize(int [],const int [],int, int);
int main()
{
int aiListX[10];
const int aiListY[5];
fnInitialize(aiListX,aiListY,10,5);
return 0;
}

void fnInitialize(int aiX[], const int aiY[],int iSizeX, int iSizeY)


{
int i;

for(i=0; i<iSizeX; i++)


aiX[i] = 0; //initialize all elements to zero

for(i=0; i<iSizeY; i++)


aiY[i] = 0; //initialize all elements to zero
}
42
#include<stdio.h>

void fnFillArray(int aiX[],int iSizeX);

int main()
{
int aiListX[10];
fnFillArray(aiListX,10);
return 0;
}
void fnFillArray(int aiX[ ],int iSizeX)
{
int i;

for(i=0;i<iSizeX;i++)
scanf (“%d”, &aiX[i]); //storing data in array
43}
#include<stdio.h>

void fnPrintArray(int aiX[],int iSizeX);

int main()
{
int aiListX[10];
fnPrintArray(aiListX,10);
return 0;
}

void fnPrintArray(int aiX[],int iSizeX)


{
int i;

for(i=0;i<iSizeX;i++)
printf (“%d”, aiX[i]); //displaying elements from array
}
44
#include <stdio.h>
//function to display array with two rows and
three columns
// function prototype void fnPrintArray (const int aiA[][3])
void fnPrintArray (const int aiA[][3]); {
int iRow; //row counter
int iColumn; //column counter
//function main begins program execution
int main() //loop through row
{ for (iROw = 0; iRow <= 1; iRow++)
{
//initialize array1, array2, array3
//output column values
int aiArray1 [2][3] = { {1, 2, 3}, {4, 5, 6} }; for (iColumn = 0; iColumn <= 2; iColumn++)
int aiArray2 [2][3] = { 1, 2, 3, 4, 5 }; {
int aiArray3 [2][3] = { {1, 2 }, { 4 } }; printf ("%d ", aiA[iRow][iColumn]);
} //end inner for
printf (“Values in array1 by row are : \n);
printf ("\n"); //start new line of output
fnPrintArray (aiArray1); } //end outer for
printf ("Values in array2 by row are : \n"); } //end function fnPrintArray
fnPrintArray (aiArray2);
printf ("Values in array3 by row are : \n");
fnPrintArray (aiArray3);
return 0;
} // end of main

45
Output

Values in array1 by row are :


123
456
Values in array2 by row are :
123
450
Values in array3 by row are :
120
400
46
#include<stdio.h>
int fnSumArray(int aiX[],int iSizeX);

int main()
{
int aiListX[10]={67,34,56,23,11,45,99,88,77,5};
int sum=0;
sum=fnSumArray(aiListX,10);
printf(“Sum is %d\n”, sum);
return 0;
}

int fnSumArray(int aiX[], int iSizeX)


{
int i,iSum = 0;

for(i=0;i<iSizeX;i++)
iSum = iSum + aiX[i]; //all elements is summed and assigned to
iSum

47
return (iSum); // returing value
}
#include<stdio.h>

int main()
{
int iSizeX=10,iCounter,iMaxValue=0;
int aiX[10]={67,34,56,23,11,45,99,88,77,5};

iMaxValue=aiX[0];
for(i=0; i<iSizeX; i++)
{
if(aiX[i] > iMaxValue )//compare largest value
with ith element
iMaxValue = aiX[i];//assign ith element as
largest value
}
48 printf(“ Maximum value is %d\n”,iMaxValue);
}
#include<stdio.h>
int fnLargestElement(int aiX[],int iSizeX);
int main()
{
int aiListX[10]={67,34,56,23,11,45,99,88,77,5};
int maxValue;

maxValue=fnLargestElement(aiListX,10);
printf(“Maximum value is %d\n ”,maxValue);
return 0;
}

int fnLargestElement(int aiX[],int iSizeX)


{
int i, iMax = aiX[0];

for(i=0; i<iSizeX; i++)


if(iMax < aiX[i])//compare largest value with ith element

iMax = aiX[i];//assign ith element as largest value


49
return (iMax);//returning largest value
#include<stdio.h>
int fnIndexLargestElement(int aiX[],int iSizeX);
int main()
{
int aiListX[10]={67,34,56,23,11,45,99,88,77,5};
int maxIndex;

maxIndex=fnIndexLargestElement(aiListX,10);
printf(“Maximum value is aiListX[%d]= %d\n ”,maxIndex,aiListX[maxIndex]);
return 0;
}

int fnIndexLargestElement(int aiX[],int iSizeX)


{
int i, iMaxIndex = aiX[0];

for(i=0; i<iSizeX; i++)


if(aiX[iMaxIndex] < aiX[i])//compare largest value with ith element

iMaxIndex = i;//assign ith element as index of largest value

return (iMaxIndex);//returning largest index value


}
50
#include<stdio.h>
{

int aiListY[10],aiListX[10]={67,34,56,23,11,45,99,88,77};
int i;

for(i=0;i<10;i++)
aiListY[i] = aiListX[i];//copy ith element from aiListX
to ith element of aiListY

for(iCounter=0;i<10;i++)
printf(“aiListY[%d] = %d\n ”,i,aiListY[i]);//display all
elements of aiListY

return 0;
}
51
#include<stdio.h>

void fnCopyArray(int aiX[],int aiY[], int iLength);

int main()
{
int aiListY[10],aiListX[10]={67,34,56,23,11,45,99,88,77};
int i;

fnCopyArray(aiListX,aiListY,10);

for(i=0;i<10;i++)
printf(“aiListY[%d] = %d\n ”,i,aiListY[i]);
return 0;
}

void fnCopyArray(int aiX[],int aiY[], int iLength)


{
int j;
for(j=0;j<iLength;j++)
aiY[j] = aiX[j];//copying jth element of aiX to jth element of aiY
52}
#include <stdio.h>
Must write squared bracket []
const int iArraySize = 10;

void fnInitializeArray (int aiX[], int iSizeX);


void fnFillArray (int aiX[], int iSizeX);
void fnPrintArray (const int aiX[], int iSizeX);
int fnSumArray (const int aiX[], int iSizeX);
int fnIndexLargestElement (const int aiX[], int iSizeX);
void fnCopyArray (const int aiX[], int aiY[], int iLength);

53
int main()
{
Omit the squared bracket
int aiListA [iArraySize] = {0};
[]
int aiListB [iArraySize];

fnPrintArray (aiListA, iArraySize);


fnInitializeArray (aiListB, iArraySize);
fnPrintArray (aiListB, iArraySize);
fnFillArray (aiListA, iArraySize);
fnPrintArray (aiListA, iArraySize);
fnSumArray (aiListA, iArraySize);
fnCopyArray (aiListA, aiListB, iArraySize);
fnPrintArray (aiListB, iArraySize);

return 0;
}

54
End – Arrays (1)

Q & A!

55

Das könnte Ihnen auch gefallen