Você está na página 1de 51

EKT120

COMPUTER PROGRAMMING

Arrays
(Part I)

Dr. Nik Adilah Hanin Bt. Zahri


adilahhanin@unimap.edu.my

1
Outline
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
What is Array?
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, iLength, iNum;
double dAverage, dTotal;
char cSelection, cChoice;

An array is a collection of a fixed number of


components wherein all of the components are of
the same type 3
What is Array?
(Example)
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;

By using array, since they are all of the same


data type, we could just write:
int aiNum[5];

4
What is Array?
(Example)
aiNum

int aiNum[5];
aiNum[0 5
] 5 components or elements in
aiNum[ 10 this array
1]
aiNum[ 15 Elements are referred to index
2]
aiNum[3 20
]
Element aiNum[2] has index 2
aiNum[ 25 and value 15
4]

5
Arrays of Data
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
address or index

6
Arrays in C
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.

7
Array Declaration
Format:
data_type array_name[int value];

Example:
int aiList[5];
const int Max_List_Size = 10;
int aiHours[Max_List_Size];
const int SIZE = 100;
double adAmount[SIZE];
const int Max_List_Size = 6;
char acAlphas[Max_List_Size];
#define N 10
double adB[N];

8
Multiple Instances vs.
Array
// multiple instance // array
int iValue1, iValue2, iValue3; int aiValue[3];
int iCount;

printf (Enter value 1: ); for(iCount=0;iCount<3;iCount++)


scanf (%d, &iValue1); {
printf(Enter value %d :,iCount);
printf(Enter value 2: ); scanf(%d,&aiValue[iCount]);
scanf(%d, &iValue2); }

printf (Enter value 3: ); // process or display


scanf(%d, &iValue3);

// process or display

9
Arrays - Memory
Allocation
Arrays are allocated int aiValue[8];
index aiValue

bulk memory 0
1
aiValue[0]=23; 2
23
Single reference used aiValue[1]=56;
3
4 56
for multiple locations aiValue[2]=100;
5
6
100
aiValue[3]=0; 7

Items are accessed aiValue[4]=12;


0

based on index aiValue[5]=234; 12

(address) with aiValue[6]=666; 234


aiValue[7]=4; 666
reference to first item
4

10
Arrays Arithmetic

Operations on arrays are similar to basic


variables.
Example:
iSum = aiNum[0] + aiNum[1] + aiNum[2];
iMultiply = 3 * aiNum[1];
iRemainder = aiNum[3] % 3;
iTotal = aiNum[1] * aiNum[2];

11
Array Initialization during
Declaration
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:
double adSales[5] = {12.25, 32.50, 16.90, 23,45.68};
adSales[0]=12.25, adSales[1]=32.50,
adSales[2]=16.90, adSales[3]=23.00, adSales[4]=45.68;

12
Array Initialization during
Declaration (cont)
Initializers:
If not enough initializes, 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

13
Array Initialization during
Declaration (cont)

When declaring and initializing arrays, it is not


necessary to specify the size of the array.
The size of the array is determined by the
number of initial values in the braces.
double adSales[]={12.25,32.50, 16.90,45.68};

14
Sample Program 1
Initializes the first 2 elements of the
aiA[]array.
#include <stdio.h>
All the other elements are then
int main()
automatically set to zero
Because no array size is given (the
{ brackets are empty) and three
int aiA[3]= {11,22}, aiB[]={44, 55, 66}; values are 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
Sample Program 1
Initializes the first 2 elements of the
aiA[]array.
#include <stdio.h>
All the other elements are then
int main()
automatically set to zero
Because no array size is given (the
{ brackets are empty) and three
int aiA[3]= {11,22}, aiB[]={44, 55, 66}; values are 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;
}

Output:

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


aiB[0]=44, aiB[1]=55, aiB[2]=66

16
Sample Program 2
#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);

return 0;
}

17
Sample Program 2
#include <stdio.h>

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

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


scanf("%d %d",&listA[0], &listB[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++)
Output:
scanf("%d",&listB[iLoop]);
Please enter two integer
for(iLoop=0;iLoop<5;iLoop++) 1 2
printf(listB[iLoop]=%d ",listB[iLoop]);
printf(\n); listA[0] = 1 listA[1] = 2
Please enter five integers
return 0; 34567
} listB[0]= 3 listB[1]= 4
listB[2]= 5
listB[3]= 6 listB[4]=7
18
Sample Program 3
#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


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

19
Sample Program 3
#include <stdio.h>
#define n 5

int main() All elements are set


{ to 0.

int list[5]={0},iLoop;

Using a loop to fill all the


for (iLoop=0;iLoop<5;iLoop++) elements of the list[]
{ array.
list[iLoop]= iLoop*100.0;
printf(list[%d]=%d\n", iLoop, list[iLoop]);
}
return 0;
}
Output:

list[0]=0
list[1]=100
list[2]=200
list[3]=300
list[4]=400

20
Sample Program 4
#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
int aiY[n]={9,6,20,5,12}; define declaration
//array statement. &
//initialization

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

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


}

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

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

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

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


}

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

void main()
{
int iLoop, iTotal = 0;

int aiY[n]={9,6,20,5,12}; For each loop


iteration, the value
for (iLoop=0;iLoop<n;iLoop++) accessed id is added
to the variable
iTotal = iTotal + aiY[iLoop]; iTotal which is
finally displayed.
printf ("\nTotal = %d\n, iTotal);
}

23
Notes
The defined constants, #define is used to
ease any future amendments of the codes,
for instance, 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.

24
Operations on Array
Storing/Reading data in an array
for (iIndex = 0; iIndex < 10; iIndex++)
scanf (%d, &aiSale[iIndex]);

Printing an array
for (iIndex = 0; iIndex < 10; iIndex++)
printf (%d , aiSale[iIndex]);

25
Parallel Arrays
Two (or more) arrays are called parallel if
their corresponding components hold
related information.

int aiStudentId[50];
char acStudentGrade[50];

26
Multi-Dimensional
Arrays

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

27
Example : 2-Dimensional Array

int aiValue[4][2];
aiValue[2][1]=5;

Column
0
1
aiValue[0][0] aiValue[0][1]
0
aiValue[1][0] aiValue[1][1]
Ro 1
w aiValue[2][0] aiValue[2][1]
2
aiValue[3][0] aiValue[3][1]
3

28
Example : 2-Dimensional Array

int aiValue[4][2];
aiValue[2][1]=5;

Column
0
1
aiValue[0][0] aiValue[0][1]
0
aiValue[1][0] aiValue[1][1]
Ro 1
w aiValue[2][0] 5
2
aiValue[3][0] aiValue[3][1]
3

29
Multi-Dimensional Arrays
(cont..)
A collection of the same type of data
stored in contiguous and increasing
memory locations.
Declaration
array_ty array_na of multi-dimensional array:
array
pe me dimension = 2

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


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

30
Multi-Dimensional Arrays
(cont..)

Multi-dimensional array can be initialized


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

31
Multi-Dimensional Arrays
(cont..)
can use braces ({ }) to separate rows in 2-
dimensional arrays
For example:
3 columns
int aiC [4][3] = {{1,
2, 3},
{4, 5, 6}, 4 rows
rows {7, 8, 9},
column {10,11,12}};
s

32
Multi-Dimensional Arrays
(cont..)
For example:

int aiC [4][3] = { {1, 2},


{4, 5, 6},
{7},
{10,11,12} };

initializes aiC[0][2], aiC[2][1] and aiC[2][2] to


be 0

int aiC [ ][3] = {{1,2, 3},


{4, 5, 6},
{7, 8, 9},
33
Notes on Arrays
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)

34
Index out of bounds
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. Example:
int aiA[10]; int iX = 10
aiA[9]=3; //ok
aiA[iX]=4;//10 is not within the range 0..9

In C, no guard against this problem


Does not check whether index value is within range
or not
Can result in accessing data of wrong memory
location
35
How to overcome?
Use defined loops

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


aiList[iLoop] = 0;

36
Passing Arrays to
Function
void fnInitialize(int aiList[])
{
int iCount;

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


aiList[iCount] = 0;
}

Initializes int array of size 5 to 0.

37
Array as Parameter in
Function
If size changes (lets say 10 or 20), need to write
another function. not practical and inflexible.
Therefore, introduce another variable, iSize.

void fnInitialize(int aiList[], int iSize)


{
int iCount;

for(iCount=0; iCount<iSize; iCount++)


aiList[iCount] = 0;
}

38
Constant Arrays
Prevent the function from changing the values in
array.
Use word const in declaration.
Function can modify array aiX but not array aiY.

void fnExample(int aiX[], const int aiY[], int


iSizeX[],int iSizeY[])
{
...
...
...
}

39
Initializing Array to 0

void fnInitializeArray (int aiX[],int iSizeX)


{
int iCounter;

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


aiX [iCounter] = 0;
}

40
Reading and Storing Data in
Array

void fnFillArray(int aiX[ ],int iSizeX)


{
int iCounter;

for(iCounter=0;iCounter<iSizeX;iCounter++)
scanf (%d, &aiX[iCounter]);
}

41
Displaying Array in a
Function

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


{
int iCounter;

for(iCounter=0;iCounter<iSizeX;iCounter ++)
printf (%d, aiX [iCounter]);
}

42
Finding and Returning Value
of Array
int fnSumArray(const int aiX[], int iSizeX)
{
int iCounter;
int iSum = 0;

for(iCounter=0;iCounter<iSizeX;iCounter++)
iSum = iSum + aiX[iCounter];

return (iSum);
}

43
Finding and Returning Index of
Largest Element of an Array
int fnIndexLargestElement(int aiX[],int SizeX)
{
int iCounter;
int iMaxIndex = 0;

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


if(aiX[iMaxIndex] < aiX[iCounter] )
iMaxIndex = iCounter;

return (iMaxIndex);
}
44
Copying an Array into
another Array
void fnCopyArray(const int aiX[],int aiY[],
int iLength)
{
int iCounter;

for(iCounter=0;iCounter<iLength;iCounter++)
aiY[iCounter] = aiX[iCounter];
}

45
Arrays in Function Prototype
#include <stdio.h>

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);

46
Passing Arrays in Function Call
int main()
{
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;
}

47
Sample Program 5
#include <stdio.h>

void fnPrintArray (const int aiA[][3]); // function prototype

//function main begins program execution


int main()
{
//initialize array1, array2, array3
int aiArray1 [2][3] = { {1, 2, 3}, {4, 5, 6} };
int aiArray2 [2][3] = { 1, 2, 3, 4, 5 };
int aiArray3 [2][3] = { {1, 2 }, { 4 } };

printf (Values in array1 by row are : \n);


fnPrintArray (aiArray1);
printf ("Values in array2 by row are : \n");
fnPrintArray (aiArray2);
printf ("Values in array3 by row are : \n");
fnPrintArray (aiArray3);
return 0;
} // end of main

48
Sample Program 5
(cont)
//function to display array with two rows and three columns
void fnPrintArray (const int aiA[][3])
{
int iRow; //row counter
int iColumn; //column counter

//loop through row


for (iROw = 0; iRow <= 1; iRow++)
{
//output column values
for (iColumn = 0; iColumn <= 2; iColumn++)
{
printf ("%d ", aiA[iRow][iColumn]);
} //end inner for

printf ("\n"); //start new line of output


} //end outer for
} //end function fnPrintArray

49
Sample Program 5
(cont)

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

50
End Arrays (1)
Q & A!

51

Você também pode gostar