CSC099 FOUNDATION COMPUTING II
ARRAY STRUCTURE
PART II
LEARNING OUTCOMES
Upon completion of this chapter, students should be able to:
• Apply concept of array in function,
• Describe concept of two-dimensional array,
• Write simple program using two-dimensional array,
• Use two-dimensional array in function.
ARRAY IN FUNCTION: PASSING INDIVIDUAL ELEMENTS
CODING OUTPUT
#include <iostream>
using namespace std;
void square(int x);
int main() {
int a[5]={2,3,4,5,6};
int i;
for(i=0;i<5;i++)
square(a[i]); Function Call
}
Pass name of the array and the elements
void square(int y) 1. Declare a variable.
2. Receive the element passed.
{
cout << y << " x " << y <<" = " << y*y << endl;
}
ARRAY IN FUNCTION: PASSING INDIVIDUAL ELEMENTS
• In function call, make sure the type of element passed
matches the function parameter type.
• Pass the individual element = Pass by value.
• The values in the element in the function call cannot be
changed by the function definition.
• In main function, loop through the array and pass each
integer element to square to print the square of each integer
element.
• In function definition, a function square displays the result
of square when receives an integer from the function call.
EXAMPLE 1: PASSING INDIVIDUAL ELEMENT
CODING OUTPUT
This program calculates the number of integer 4 found
in the set of the following array.
#include <iostream>
using namespace std;
void print(int m);
int count = 0;
int main() {
int i,ary1[5]={6,4,2,4,3};
for(i=0; i<5; i++)
print(ary1[i]);
cout << "Number of integer 4 in the array is " << count << endl;}
void print(int m) {
if ( m == 4)
count++;
}
EXAMPLE 2: TO PRODUCE FREQUENCY DISTRIBUTION
• Common statistical application using array
• Frequency distributions and histograms
• Use frequency array to show number of identical element in
a series of number
• Histograms shows a pictorial representation of a frequency
array
EXAMPLE 2: TO PRODUCE FREQUENCY DISTRIBUTION (CONT’D)
Scenario :
You are assigned to write a program to calculate the response (5-Strongly Not Agree, 4-Not Agree, 3-
OK, 2-Agree, 1-Strongly Agree) of 10 students regarding the difficulties of C Programming.
Students’ Responses
response[0] Frequency Array Statistics of Response
Strongly Agree :*
Agree :*
.. frequency[0]
OK :***
.. frequency[1] Disagree :*
.. frequency[2] Strongly disagree :****
..
frequency[3]
frequency[4]
response[8]
response[9] frequency
response
EXAMPLE 2: SAMPLE PROGRAM
#include <iostream> cout << "\nStatistic of Response";
using namespace std; cout << "\n---------------------";
#define MAX_RESPONSE 10 cout << "\n(1) Strongly Agree\t\t : ";
void displayData(int); displayData(SAgree);
int main() cout << "\n(2) Agree\t\t\t : ";
{ displayData(Agree);
int response[MAX_RESPONSE]; cout << "\n(3) OK\t\t\t\t : ";
int frequency[5]={0}; displayData(OK);
int i=0; cout << "\n(4) Not Agree\t\t\t : ";
int SAgree = 0, Agree = 0, OK = 0, NAgree = 0, displayData(NAgree);
SNAgree = 0; cout << "\n(5) Strongly Not Agree\t\t : ";
displayData(SNAgree);
do
{ return 0;
cout << "\nC Programming is difficult\n"; }
cout << "1. Strongly Agree\t 2. Agree\t 3.OK\t
4.Not Agree\t 5.Strongly Not Agree\n "; void displayData(int maxNum)
cin >> response[i]; {
i++; int i=0;
}while(i<MAX_RESPONSE); for(i=0; i<maxNum; i++)
cout << "* ";
for(i=0; i<MAX_RESPONSE; i++) }
{
if(response[i] == 1)
SAgree++;
else if(response[i] == 2)
Agree++;
else if(response[i] == 3)
OK++;
else if(response[i] == 4)
NAgree++;
else if(response[i] == 5)
SNAgree++;
}
EXAMPLE 2: OUTPUT
EXERCISE 1: PASSING INDIVIDUAL ELEMENT
CODING OUTPUT
Trace for the output.
int power(int x);
int main()
{
int a, b, array[4]={3,5,2,7};
for( a=0; a<4; a++)
{
b = power(array[a]);
cout << a+1 << ". " << b << "\n";
}
}
int power(int x)
{
x = pow(x,2);
return x;
}
ARRAY IN FUNCTION: PASSING THE WHOLE ARRAY
• When passing by value (individual element) from huge array to a
function, additional memory is required to allocate a copy of its
elements
• E.g : if an array containing 20k elements were passed by value to
a function, another 20k elements would have to be allocated in
the function and each element would have to be copied from
one array to another.
• Solution: pass the whole array to a function - the called function
can modify the element values in the callers’ original arrays.
• When the called function modifies array elements in its function
body, it’s modifying the actual elements of the array in their
original memory locations.
ARRAY IN FUNCTION: PASSING THE WHOLE ARRAY
• Two rules associated with passing the whole array
• The function must be called by passing only the name of the
array
• In the function definition, the formal parameter must be an
array type but specifying the size of the array is not
required
• A function can change the elements in array by passing the
array name without the constant modifier.
EXAMPLE 1: PASSING THE WHOLE ARRAY
CODING ILLUSTRATION & OUTPUT
#include <iostream> Before After
using namespace std;
void update_stock(int x[]);
Declare an array 1 stock[0] 1
int main() variable without
{ size 2 stock[1] 4
int stock[5]={2,3,4,5,6};
update_stock(stock); Pass only name
3 stock[2]
9
} of the array
void update_stock(int x[]) 4 stock[3]
16
{
int i; stock[4]
5 25
for(i=0;i<5;i++)
cout << x[i] << " * " << x[i] << " = " <<
x[i] * x[i] << endl; x is pointing to the
} x first address of stock
*Element in an array can be changed by passing the array name i.e. stock[0]
- Without constant modifier.
EXAMPLE 2: PASSING THE WHOLE ARRAY FOR UPDATING
CODING OUTPUT
#include <iostream>
using namespace std;
void student(int x[]);
int main()
{
int i, marks[10]={1,2,3,6,1,1,1,1};
student(marks);
cout << "After call is ";
for( i=0; i<10; i++)
cout << marks[i] << " ";
}
void student(int x[])
{
int i;
for(i=0; i<10; i++)
x[i] += 5;
}
EXERCISE 1: PASSING THE WHOLE ARRAY
CODING OUTPUT
#include <iostream>
#include <iomanip>
using namespace std;
void number(float k[])
{
for (int i = 0; i < 4; i++)
k[i] *= 1 - 0.5;
}
int main()
{
float price[4] = {100.2, 90.0, 76.2, 8.90};
number(price);
cout<< fixed << setprecision(2);
cout << "new price for" << endl;
for (int i = 0; i < 4; i++)
cout << "item " << i + 1 << " is RM " << price[i] << endl;
return 0;
}
PASSING AN ARRAY AS CONSTANT
• Use type qualifier const to prevent modification of array
values in a function.
• When an array parameter is preceded by the const qualifier,
the array elements become constant in the function body,
and any attempt to modify an element of the array in the
function body results in a compile-time error.
PASSING THE WHOLE ARRAY FOR UPDATING (USING CONSTANT MODIFIER)
#include <stdio.h>
using namespace std;
void update(const int x[]);
int main()
{
int stock[5]={1,2,3,4,5};
update(stock);
Const
declared
ERROR!!!
}
ERROR!!! Modifying the
void update(const int x[])
elements of the array
{
int i;
for(i=0;i<5;i++)
cout << x[i] << " * " << x[i] << " = " << x[i] = x[i] * x[i] << endl;
}
The example of an ERROR
error: assignment of read-only location '*(x + (unsigned int)((unsigned int)i * 4u))’ that you will encounter.
PASSING THE WHOLE ARRAY FOR UPDATING (USING CONSTANT MODIFIER)
CODING OUTPUT
#include <iostream>
#include <iomanip>
using namespace std;
float average(const int y[]); THE CORRECT
WAY
int main()
{
Constant
int stock[5]={3,7,2,4,5};
float av;
modifier
av = average(stock); declared
cout << "Average = " <<
fixed << setprecision(2) << av;
}
float average(const int y[])
{
int i;
float tot = 0, avg;
for(i=0; i<5; i++)
tot = tot + y[i];
avg = tot / 5;
return avg;
}
TEST YOUR UNDERSTANDING 1
QUESTIONS ANSWERS
1. Write a Function Call to pass an element in
array mark[] to a function average. The
array consists 5 elements. (Hint: use for
loop)
2. Write a Function Call to pass the whole
array mark[] to a function average.
3. Write a Function Prototype for function
average to receive an array mark[] as a
constant integer and return an integer.
TWO-DIMENSIONAL ARRAY
• It often happens that you want to store a collection of
values that have a two-dimensional layout.
• Such as sets commonly occur in financial and
scientific applications.
• An arrangement consisting rows and columns of
values is called two-dimensional arrays
SINGLE DIMENSIONAL ARRAY VS. TWO-DIMENSIONAL ARRAY
USING AN ARRAY USING 2-DIMENSIONAL ARRAY
DECLARATION DECLARATION
int mark[4]; rows int table[5][3]; columns
ILLUSTRATION ILLUSTRATION
11 12 13
[0,0] [0,1] [0,2]
17 18 19 20
24 25 26
[0] [1] [2] [3] [1,0] [1,1] [1,2]
37 38 39
[2,0] [2,1] [2,2]
40 41 42
[3,0] [3,1] [3,2]
53 54 55
[4,0] [4,1] [4,2]
DECLARATION AND INITIALIZATION
• Two-dimensional array declaration
int table[5][4]; Second dimension specifies
First dimension specifies the the number of columns in
number of rows in the array each row
• Different ways of Two-dimensional array initialization
A ) int table[5][4] = {0,1,2,3,10,11,12,13,20,21,22,23,30,31,32,
31,40,41,42,43};
B) int table[5][4] = {{0,1,2,3},{10,11,12,13},{20,21,22,23},
{30,31,32,31},{40,41,42,43}};
c) int table[5][4] =
{{0,1},{10},{20,21,22},{30},{40,41,42,43}};
TWO-DIMENSIONAL ARRAY : ACCESSING VALUES
• To access the element of a two-dimensional array, the index of row
and column are used.
Example: To print the element in the second row and the third column of table
int table[5][4] =
{{0,1,2,3},{10,11,12,13},{20,21,22,23},
{30,31,32,31},{40,41,42,43}};
cout << table[1][2];// print 12
• Individual elements can be initialized using the assignment
operator.
table[2][0] = 23;
TWO-DIMENSIONAL ARRAY : INPUT/OUTPUT VALUES
Input Values
for(r=0;r<5;r++)
for(c=0;c<4;c++)
cin >> table[r][c];
Output Values
for(r=0;r<5;r++)
for(c=0;c<4;c++)
cout << table[r][c] << endl;
EXAMPLE 1: TWO-DIMENSIONAL ARRAY
CODING OUTPUT
#include <iostream>
using namespace std;
int main()
{
int i,j,ary1[4][3];
for(i=0; i<4; i++)
{
cout << "\nEnter 3 numbers for row " << i + 1 << ": ";
for(j=0; j<3; j++)
cin >> ary1[i][j];
}
cout << "\nElements of ary1 is : \n";
for(i=0; i<4; i++){
for(j=0; j<3; j++)
cout << ary1[i][j] << "\t";
cout << "\n";
}
}
TWO-DIMENSIONAL ARRAY : ASSIGN VALUES
• Let us assume that we want to assign values to 5 x 4 array
as shown below.
0 1 2 3
10 11 12 13
20 21 22 23
30 31 32 33
40 41 42 43
• The following code performs the initialization of the above :
int table[5][4];
for(r=0;r<5;r++)
for(c=0;c<4;c++)
table[r][c]= r*10 + c ;
PASSING A TWO-DIMENSIONAL ARRAY TO FUNCTION
• Passing an individual element
• Pass the individual element by indexing the array name with
the row number and the column number
• Passing the whole array
• Use the array name as the actual parameter
EXAMPLE 1: PASSING AN INDIVIDUAL ELEMENT
CODING OUTPUT
int main() {
int
i,j,ary1[4][3]={{1,2,3},{2,4,6},{3,6,9},{
3,2,1}};
1 2 3
for(i=0; i<4; i++){
for(j=0; j<3; j++) 2 4 6
display(ary1[i][j]); 3 6 9
printf("\n"); 3 2 1
}
} Pass an individual element
void display(int a) {
printf("%5d",a);
}
EXAMPLE 2: PASSING THE WHOLE ARRAY
CODING OUTPUT
#include <iostream>
#include <string>
using namespace std;
void display(const int x[4][3]);
int main() {
int table[4][3]={{0,1,2},{10,11,12},{20,21,22},{30,31,32}};
display(table);
cout << "\n"; Pass the whole 0 1 2
} array
10 11 12
void display(const int x[4][3]) { 20 21 22
int col,row;
for(row=0; row<4; row++) { 30 31 32
for(col=0; col<3; col++) {
cout << x[row][col] << "\t"; Display the current element
} of the row. Eg:
cout << "\n"; loop 1 x[0,0] = 0
} loop 2 x[0,1] = 1
} loop 3 x[0,2] = 2
TEST YOUR UNDERSTANDING 2
QUESTIONS ANSWERS
1. Write a Function Call to pass an element of
number[i][j] to a function show. (Hint: use
for loop)
2. Write Function Prototype of question no. 1.
This function does not return any value and
the size is 3 x 4. The data type received in the
parameter is a type of integer.
3. Write a Function Call to pass the whole array
grid to a function show.
4. Write Function Prototype of question no. 3.
This function does not return any value and
the size is 4 x 5. The data type received in the
parameter is a type of integer.
EXERCISE 1
Which one is using pass by individual method?
A B
int main() int main()
{ {
int num[5]={0,1,2,3,4}; int a[5]={1,2,4,5,9};
square(num); int i;
}
for(i=0;i<5;i++)
square(a[i]);
void square(int a[]) }
{
int i; void square(int x)
for(i=0;i<5;i++) {
cout << (a[i] = a[i] + 1) << cout << x + 1 << endl;
endl; }
}
EXERCISE 2: PASSING AN INDIVIDUAL ELEMENT
QUESTION ANSWER
Write a program that passes an
individual element of an array from
main() to a funct(). The funct()
returns the element if the element is
divisible by 3. Otherwise, it returns 0.
Calculate the sum of the returned
elements and display the sum in main().
int array [ 5 ] ={10, 11, 3, 9, 7};
EXERCISE 3: 2D ARRAY
QUESTIONS ANSWERS
Write the C++ statements for each of the following.
1. Declare a two-dimensional array named match[][]
of type integer. This array consists of 4 rows and 3
columns.
2. By using for loop, store 1 in the first row and 2 in the
remaining rows.
3. Display the content of the array match[][].
EXERCISE 4: FIND THE ERRORS
1. #include <iostream>
2. using namespace std;
3. void display(int a[ ])
4. int main()
5. {
6. int i,j,ary1[3][3]={{1,2,3},{2,4,6},{3,6,9},{3,2,1}};
7. for(i=0; i<3; i++);
8. {
9. for(j=0; j<3; j++);
10. display(ary1[i]);
11. cout << "\n";
12. }
13. return 0;
14. }
15. void display(int a[ ]);
16. {
17. cout << a[ ] << " ";
18. }
EXERCISE 5: TRACING
CODING OUTPUT
int main() {
int a[5] = { 0, 1, 2, 3, 4 }, i;
cout << "Effects of passing entire array by reference.";
cout << "\n\nThe values of the original array are:\n";
for (i = 0; i < 5; i++)
cout << " " << a[i];
cout << "\n";
modifyArray(a, 5);
cout << "The values of the modified array are:\n";
for (i = 0; i < 5; i++) { void modifyArray( int b[], int size )
cout << " " << a[i]; {
} int j;
return 0;
} for ( j = 0; j < size; j++ )
b[ j ] *= 2;
}
EXERCISE 6: PASSING THE WHOLE ARRAY
QUESTION ANSWER
Write a C program that declares an array
alpha of 20 elements of type integer.
Pass the whole array to a function
number().
In function number(), assign the first 10 Take
elements to be equal to its own index Home
number, and the last 10 elements are
equal to three times of its own index Exercise
number.
Display the array in main() so that 10
elements per line are printed.
EXERCISE 7: ADDITION OF THE MATRICES
QUESTIONS ANSWERS
Write a C program that performs
the addition of the matrices below.
C=A+B
given Take
Home
𝟐𝟐 𝟓𝟓 𝟑𝟑 𝟗𝟗 Exercise
𝑨𝑨 = B=
𝟒𝟒 𝟕𝟕 𝟏𝟏 𝟖𝟖
CONCLUSION
We have learnt the following:
• Array in function: passing individual elements and the
whole array
• Produce frequency distribution
• Passing an array as constant as well as for updating
• Two-dimensional array
• Passing an individual element and passing the whole
array in two-dimensional array
REFERENCES
1) Aminatul Solehah Idris, Jasrul Nizam Ghazali, Mohamad Norzamani Sahroni, Muhd Eizan
Shafiq Abdul Aziz, Noorazida Mohd Idris, Norzaidah Md Noh, Nurhilyana Anuar, Raudzatul
Fathiyah Mohd Said, Teh Faradilla Abdul Rahman, Zakiah Noh, Zamri Abu Bakar,
Practical C++ for Beginners, 1st, Djuta Dallek Enterprise, 2025, ISBN: 978-629-95317
2) Paul Dietel, Harvey Dietel, C How to Program, 7, Pearson, 2013, ISBN: 9780273776840
3) H. H. Tan, T.B D'Orazio, S.H Or, & Marian M.Y. Choy, C Programming, McGraw Hill, 2012,
ISBN: 9780071311168
4) E. Balagurusamy, Programming in Ansi C, 6, Tata McGraw-Hill Education, 2012, ISBN:
9781259004612
5) D. S. Malik, C++ Programming, 5, Cengage Learning, 2011, ISBN: 9780538798136
6) Jeri R. Hanly,Elliot B. Koffman, Problem Solving and Program Design in C, 6, Prentice Hall,
2010, ISBN: 9780321601513
7) Alan Evans, Kendall Martin, Mary Anne Poasty, Technology in Action, 11, Pearson, 2015,
ISBN: 129208235