Array p1 PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 71

EKT150 INTRODUCTION TO

COMPUTER PROGRAMMING
Array
Part I

Dr. Nur Farhan Kahar, Dr. Nur Hafizah Ghazali


School of Computer & Communication Engineering
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=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
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; //declaration

//assign numbers to every variable


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

4
What is Array? (Example)
By using array, since they are all of the same data type, we
could declare them as an array:
Declaration int person[5]; aiNum

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


Element
element aiNum[1]=10; aiNum[1] 10 aiNum[1] has
with index index 1 and value
number 0 aiNum[2]=15; aiNum[2] 15 10
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
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 index or address

6
Array Declaration 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.
int aiNum[5];
float afNum[7];
double adNum[8];
char acName[10];
7
Arrays - Memory Allocation

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 aiNum[5]=234; 5 234


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

8
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:

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
Array Initialization during Declaration
(cont…)
• 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 of
10
the array.
Multiple Instances vs. Array
1&2
// 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 Instances vs. Array
1&2
// multiple instance // array
int iValue1, iValue2, iValue3; int aiValue[3];
int i; Using Loops

printf (“Enter value 1: “); for(i=0;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
Operations on Array
• 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
Operations on Array
• 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
aiSale[4] 39 39 14
Sample Program 1
Initializes the first 2 elements of the aiA[]array.
All the other elements are then automatically
#include <stdio.h> set to zero
int main()
{ Because no array size is
int aiA[3]= {11,22}, aiB[]={44, 55, 66};
given (the brackets are
empty) and three values are
given in braces, the array is
printf(“aiA[0]=%2d, aiA[1]=%2d, aiA[2]=%2d \n”,
aiA[0],aiA[1],aiA[2]); automatically declared to
have a size of 3 with the
printf(“aiB[0]=%2d, aiB[1]=%2d, aiB[2]=%2d \n", value shown being the
aiB[0],aiB[1],aiB[2]); initial element values.

return 0;
}

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

listB[0]=10
return 0;
}
17
Sample Program 2 3
#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++)
Output:
scanf("%d",&listB[iLoop]);
Please enter two integer
for(iLoop=0;iLoop<5;iLoop++) 1 2
printf(“listB[%d]=%d ",iLoop,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
18
Arrays Arithmetic
• 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
Definition of Constants

• 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

20
Sample Program 3
4
#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<n;iLoop++)
{
list[iLoop]= iLoop*100.0;
printf(“list[%d]=%d\n", iLoop, list[iLoop]);
}
return 0;
}

21
21
Sample Program 3
4
#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<n;iLoop++)
{
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

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

void main() ⚫ the array size n is


{ declared in the define
int iLoop, iTotal = 0; //variable
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);


}

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

void main()
{
int iLoop, iTotal = 0; ⚫
//variable
program declares and
initializes 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);


}

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

void main()
{
int iLoop, iTotal = 0;
⚫ For each loop
iteration, the value
int aiY[n]={9,6,20,5,12};
accessed id is added
for (iLoop=0;iLoop<n;iLoop++) to the variable
iTotal = iTotal + aiY[iLoop]; iTotal
printf ("\nTotal = %d\n”, iTotal);
}

25
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 (iLoop=0;iLoop<n;iLoop++)
iTotal = iTotal + aiY[iLoop]; ⚫ Display the value
printf ("\nTotal = %d\n”, iTotal); of variable iTotal
}

26
Exercise 1
Trace and predict the output of the following program:
6
#include<stdio.h>

int main()
{
int aList[5]={9,6,20,5,12};
int i=0;

for (i=4;i>=0;i--)
printf (“aList[%d] = %d\n”, i, aList[i]);
return 0;
}

27
Sample Program 5 :
Copying an Array into another Array
#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(i=0;i<10;i++)
printf(“aiListY[%d] = %d\n ”,i,aiListY[i]);//display all
elements of aiListY

return 0;
}

28
Sample Program 5 :
Copying an Array into another Array
#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(i=0;i<10;i++)
printf(“aiListY[%d] = %d\n ”,i,aiListY[i]);//display all
elements of aiListY
aiListY[0] = 67
return 0; aiListY[1] = 34
aiListY[2] = 56
} …
aiListY[8] = 88
aiListY[9] = 77 29
Sample Program 6:
Finding Largest Value of an Array 7

#include<stdio.h>

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

iMaxValue=aiX[0];
for(i=0; i<iSizeX; i++)
{
//compare largest value with ith element
if(aiX[i] > iMaxValue)
iMaxValue = aiX[i];//assign ith element as
largest value
}
printf(“ Maximum value is %d\n”,iMaxValue);
}
30
Sample Program 6:
Finding Largest Value of an Array 7

#include<stdio.h>

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

iMaxValue=aiX[0];
for(i=0; i<iSizeX; i++)
{
//compare largest value with ith element
if(aiX[i] > iMaxValue)
iMaxValue = aiX[i];//assign ith element as
largest value
}
printf(“ Maximum value is %d\n”,iMaxValue);
}
Maximum value is 99 31
Sample Program 7:
Finding Largest Index of an Array 8
#include<stdio.h>

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

iMaxIndex=0;
for(i=0; i<iSizeX; i++)
{
//compare largest value with ith element
if(i > iMaxIndex)
iMaxIndex = i;//assign ith element as largest
value
}
printf(“ Maximum index is %d\n”,iMaxIndex);
}
32
Sample Program 7:
Finding Largest Index of an Array 8

#include<stdio.h>

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

iMaxIndex=0;
for(i=0; i<iSizeX; i++)
{
//compare largest value with ith element
if(i > iMaxIndex)
iMaxIndex = i;//assign ith element as largest
value
}
printf(“ Maximum index is %d\n”,iMaxIndex);
}
Maximum index is 6 33
Parallel Arrays
• 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


1410073 acStudentGrade[2] C
aiStudentld[2]
aiStudentId[3] 1400074 acStudentGrade[3] A

aiStudentId[4] 1400075 acStudentGrade[4] B

34
Parallel Arrays
• 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 afWeightPound[2] 7.71
afWeightKg[2]
afWeightKg[3] 4.5 afWeightPound[3] 9.92

afWeightKg[4] 5.5 afWeightPound[4] 12.13

35
Sample Program 8 9

#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}; Weight in kg from ith element of array
float sumPound=0,sumKg=0;
afWeightKg is converted to pound and
assigned to ith element of array
afWeightPound
for (i=0;i<n;i++)
{
Weight in kg from ith element of array
afWeightPound[i] = afWeightKg[i] * 2.204;
sumKg=sumKg+afWeightKg[i]; afWeightKg is summed and assign to sumKg
sumPound=sumPound+afWeightPound[i]; Weight in pound from ith element of array
}
afWeightPound is summed and assign to
sumPound
for (i=0;i<n;i++)
printf(“afWeightPound[%d]=%f\n”,i,afWeightPound[i]);

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


} 36
Exercise 2
Trace and predict the output of the following program given input by
user are {1,3,5,7,9}:
#include <stdio.h>
int main()
{
int aListA[5],aListB[5],i,sum=0;

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

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

for(i=0;i<5;i++)
{
aListB[i]=aListA[i]+i;
sum=sum+aListB[i];
}
for(i=0;i<5;i++)
printf(“aListB[i]=%d\n",aListB[i]);

printf(“Sum is %d\n”,sum);
return 0;
37
}
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

38
Example : 2-Dimensional Array

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]

39
Example : 2-Dimensional Array

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]

40
Multi-Dimensional Arrays
• 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 second row
first row
initial values initial values

Column 0 1 2
0 aiNum1[0][0] aiNum1[0][1] aiNum1[0][2]
Row
51 52 53
aiNum1[1][0] aiNum1[1][1] aiNum1[1][2]
1
54 55 56 41
Initialization in Declaration Statement

1. In previous example, the multi-dimensional array is


initialized directly in the declaration in one line:
– 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.

42
Initialization in Declaration Statement
2. Initialization using braces ({ }) to separate rows in
2-dimensional arrays
Example 1:
3 columns

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


{4, 5, 6}, 4 rows
rows {7, 8, 9},
columns {10,11,12}};

43
Initialization in Declaration Statement
Example 2:
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

Example 3:
int aiNum[ ][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10,11,12}};
• implicitly declares the number of rows to be 4
44
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)

45
Sample Program 9
#include <stdio.h>
int main()
{
float aListA[2][3]={0},sum=0;
int i,j;

printf(“Enter 6 integers: ”);

for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf(“%f”,&aListA[i][j]);

for(i=0;i<2;i++){
for(j=0;j<3;j++){
printf(“aListA[%d][%d]=%f\n”,i,j,aListA[i][j]);
sum=sum+aListA[i][j];
}}

printf(“Sum is %2.f\n”,sum);

return 0;
} 46
Sample Program 9
#include <stdio.h>
int main()
{
float aListA[2][3]={0},sum=0;
Please enter five integers
int i,j; 11 22 33 44 55 66
printf(“Enter 6 integers: ”); aListA[0][0] = 11
aListA[0][1] = 22
aListA[0][2] = 33
for(i=0;i<2;i++)
aListA[1][0] = 44
for(j=0;j<3;j++) aListA[1][1] = 55
scanf(“%f”,&aListA[i][j]); aListA[1][2] = 66
Sum is 231
for(i=0;i<2;i++){
for(j=0;j<3;j++){
printf(“aListA[%d][%d]=%f\n”,i,j,aListA[i][j]);
sum=sum+aListA[i][j];
}}

printf(“Sum is %2.f\n”,sum);

return 0;
} 47
Exercise 3
#include <stdio.h>
int main()
{
float aListA[2][3]={0},sum=0;
int i,j;

printf(“Enter 6 integers: ”);

for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf(“%f”,&aListA[i][j]);

for(i=2;i>0;i--){
for(j=3;j>0;j--){
printf(“aListA[%d][%d]=%f\n”,i,j,aListA[i][j]);
sum=sum+(aListA[i][j]*aListA[i][j]);
}}

printf(“Sum is %.2f\n”,sum);

return 0;
} 48
Exercise 4
Complete the following C program to copy a 2-dimensional array of
aiListX[][] to aiListY[][]. At the end of the program, display the index and
element of array aiListY[][].
#include<stdio.h>
{
int aiListY[2][5], aiListX[2][5]= {67, 34, 56, 23, 11, 45,
99, 88, 77};
int i,j;

//copy the list of aiListX to aiListY using nested loop

//display the index and element of aiListY[][]

return 0;
}

49
Exercise 5
Complete the following C program to find the largest value from a
2-dimensional array of aiX[][]. At the end of the program, display the
largest value.
#include<stdio.h>

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

//find largest value from aiX using nested loops

//display the largest value from 2d array


return 0;
}

50
Exercise 6
Complete the following C program to find the index of row and column
which contains the largest value from a 2-dimensional array of aiX[][]. At
the end of the program, display both index.
#include<stdio.h>
int main()
{

int i,j,iMaxRowIndex=0,iMaxColumnIndex=0;
int aiX[2][5]={67,34,56,23,11,45,99,88,77,5};

//find index of row and column for largest value from aiX
using nested loops

//display the both index values

return 0; }

51
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
aiNum
Example:
X
int aiNum[5];
aiNum[-1]=1;//out of bound aiNum[0] 3
aiNum[1]=3; //ok aiNum[1] 6
aiNum[2]=6; //ok
aiNum[5]=4;//out of bound aiNum[2]
aiNum[3]
aiNum[4]
X
• In C, no guard against this problem
– Without checking whether index value is within range or not
can result in accessing data of wrong memory location
52
How to overcome?
• Use defined loops

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


aiList[iLoop] = 0;

53
Passing Arrays to Function
#include<stdio.h>
void fnInitialize(int []);
int main()
{
int aiListX[5]; //declaration of array
// passing array to function fnInitialize
fnInitialize(aiListX);
return 0;
}

void fnInitialize(int aiList[])


{
int i;
for(i=0; i<5; i++)
aiList[i] = 0; //initialize all elements to 0
}
54
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.

#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;
for(i=0; i<iSize; i++)
aiList[iCount] = 0;
}
55
Passing Multiple Arrays to Function
#include<stdio.h>
void fnInitialize(int [],int [],int, int);
int main()
{
int aiListX[10];
int aiListY[5];
fnInitialize(aiListX,aiListY,10,5);
return 0;
}

void fnInitialize(int aiX[], 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
}

56
Reading and Storing Data in Array
using Function
#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
}
57
Displaying Array using Function
#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
}
58
Displaying 2-Dimensional Array using
Function
#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 };

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


fnPrintArray (aiArray1);
printf ("Values in array2 by row are : \n");
fnPrintArray (aiArray2);

return 0;
} // end of main

59
Displaying 2-Dimensional Array using
Function (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

60
Displaying 2-Dimensional Array using
Function (cont…)
Output

Values in array1 by row are :


123
456
Values in array2 by row are :
123
450

61
Finding and Returning Value of Array
using Function
#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

return (iSum); // returing value


} 62
Finding and Returning Largest
Element of an Array using Function
#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
return (iMax);//returning largest value
}

63
Finding and Returning Index of Largest
Element of an Array using Function
#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
}

64
Copying an Array into another Array
using Function
#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;

fnCopy(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
} 65
Arrays in Function Prototype

#include <stdio.h>

const int iArraySize = 10; Must write squared bracket []

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

66
Passing Arrays in Function Call
int main()
{
int aiListA [iArraySize] = {0}; Omit the squared bracket []
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;
}

67
Past Year Questions ( Final 2016/2017)
The C program in the following figure declares a) Modify and add C statements in line 12 so
2-dimensional array of integer and display all that the program finds odd number and
elements from the array. The following questions even number from the array. Added C
are based on the following C program. statements should produce the following
output:
1 #include<stdio.h>
2 Number[0][0]=31 Odd number
3 int main () Number[0][1]=98 Even number
4 { Number[1][0]=67 Odd number
5 int number[5][2]= {31, 98, 67, 15, …
82, 74, 29, 53, 5, 102}; Number[4][0]=5 Odd number
6 int i,j; Number[4][1]=102 Even number
7
8 for(i=0;i<5;i++)
9 {
10 for(j=0;j<2;j++)
11 {
12 printf("number:%d\n", b) Rewrite for nested loop in the program so
number[i][j]); that the output produce in (a) can be
13 } displayed in reversed order.
14 }
15 return 0;
16 }
Past Year Questions ( Final 2016/2017)
• The following Figure 4(b) contains incomplete programs that perform
addition of all elements from array numList. Write a function definition
for the function prototype in line 7.
#include<stdio.h>

int addition(int numList[],int size);

int main()
{

int numList[]={45,32,12,9,27,93,86,50,64,77};
int i,size=10,add=0;

add=addition(numList,size);

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

printf(“Addition value is %d\n”,add);

return(0);
}
Past Year Questions ( Final 2014/2015)
• By using two dimensional arrays, weight declared in Figure 7, produce a C program
using nested loops to accept and assign input data of weight to fill in the array. In the
same loop, produce C statements to determine the minimum input value from the
array. At the end of the program, display the minimum value. The outer loop should
represents the number of rows and the inner loop should represents the number of
column.
#include <stdio.h>

int main(void)
{
float weight[4][2]={0};
float min=10000, total=0;
int i,j;

return 0;
}
End – Arrays (1)
Q & A!

71

You might also like