Professional Documents
Culture Documents
Array p1 PDF
Array p1 PDF
Array p1 PDF
COMPUTER PROGRAMMING
Array
Part I
• Example:
int iCount=15; int iCount 15
3
What is Array? (Example)
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
6
Array Declaration in C
• Arrays can assume any type (including the
primitive data types)
int, char, double, float, etc.
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
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:
OR
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} ;
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];
11
Multiple Instances vs. Array
1&2
// multiple instance // array
int iValue1, iValue2, iValue3; int aiValue[3];
int i; Using Loops
// 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:
int main()
{
int listA[2],listB[5],iLoop;
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;
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
19
Definition of Constants
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
for (iLoop=0;iLoop<n;iLoop++)
iTotal = iTotal + aiY[iLoop];
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];
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’};
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};
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]);
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];
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
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
42
Initialization in Declaration Statement
2. Initialization using braces ({ }) to separate rows in
2-dimensional arrays
Example 1:
3 columns
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;
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;
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;
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};
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
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
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;
}
#include<stdio.h>
void fnInitialize(int [],int);
int main()
{
int aiListX[10];
int iSize=10;
fnInitialize(aiListX,iSize);
return 0;
}
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>
int main()
{
int aiListX[10];
fnPrintArray(aiListX,10);
return 0;
}
for(i=0;i<iSizeX;i++)
printf (“%d”, aiX[i]); //displaying elements from array
}
58
Displaying 2-Dimensional Array using
Function
#include <stdio.h>
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
60
Displaying 2-Dimensional Array using
Function (cont…)
Output
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;
}
for(i=0;i<iSizeX;i++)
iSum = iSum + aiX[i]; //all elements is summed and assigned to
iSum
maxValue=fnLargestElement(aiListX,10);
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;
}
64
Copying an Array into another Array
using Function
#include<stdio.h>
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;
}
#include <stdio.h>
66
Passing Arrays in Function Call
int main()
{
int aiListA [iArraySize] = {0}; Omit the squared bracket []
int 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 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]);
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