PDF Document
PDF Document
Array Structure
PART 2
✔Passing Array in function parameter
✔Two-Dimensional Array
Learning Outcomes
•At the end of this lesson, students should be able:
•To apply concept of array in function,
•To describe concept of two-dimensional array,
•To write simple program using two-dimensional
array,
•To use two-dimensional array in function.
Array in function: Passing individual elements
1. Declare a variable.
2. Receive the element
#include <stdio.h> void square(int x)
passed.
{
void square(int x); printf(" %d x %d = %d\n",x,x, x*x);
int main() }
{
int a[5]={1,2,3,4,5};
int i;
for(i=0;i<5;i++)
square(a[i]);
Pass name of
} function call the array and
the elements
3
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
4
Example 1 - Passing individual element
This program calculates the number of integer 4 found in the set of the following array.
#include <stdio.h>
void print(int m);
int count = 0;
int main()
{
int i,ary1[5]={6,4,2,4,3}; void print(int m)
{
for(i=0; i<5; i++) if ( m == 4)
{ count++;
print(ary1[i]);
}
}
printf(“Number of integer 4 in the array is
%d\n", count);
} 5
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
6
Example 2: To Produce Frequency
Scenario : Distribution (cont’d)
You were assigned to write 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
7
for(i=0; i<MAX_RESPONSE; i++)
++frequency[--response[i]];
Sample Program printf("\nStatistic of Response");
printf("\n---------------------");
#include <stdio.h> printf("\nStrongly Agree\t\t : ");
#define MAX_RESPONSE 10 displayData(frequency[0]);
void displayData(int); printf("\nAgree\t\t\t : ");
displayData(frequency[1]);
printf("\nOK\t\t\t: ");
int main(){ displayData(frequency[2]);
int response[MAX_RESPONSE]; printf("\nNot Agree\t\t : ");
int frequency[5]={0}; displayData(frequency[3]);
int i=0; printf("\nStrongly Not Agree\t : ");
displayData(frequency[4]);
do{ }
printf("\nC Programming is difficult\n");
printf("1. Strongly Agree\t 2. Agree\t 3.OK\t
4.Not Agree\t 5.Strongly Not Agree\n "); void displayData(int maxNum){
scanf("%d", &response[i]); int i=0;
i++; for(i=0; i<maxNum; i++)
}while(i<MAX_RESPONSE); printf("* ");
}
Example 2 : Output
9
Exercise 1 – Passing individual element
Trace for the output
int power(int x)
int power(int x); {
int main(void) x = pow(x,2);
{ return x;
int a, b, array[4]={1,2,3,6}; }
for( a=0; a<4; a++)
{
b = power(array[a]);
printf("%d. %d\n", a+1, b);
}
}
10
Array in function: Passing the whole
array
• Need an extra memory to allocate values/elements
when passing by value the whole huge array to a
function
• 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 array to a function by reference—the
called function can modify the element values in the
callers’ original arrays. 11
Array in function: Passing the whole arrays
• The name of the array evaluates to the address of the first element of
the array.
• Because the starting address of the array is passed, the called function
knows precisely where the array is stored.
• 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.
12
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, the
size of the array doesn’t need to be specified
• A function can change the elements in array by passing the array name
without the constant modifier.
13
Example 3: Passing the whole array
Before After
#include <stdio.h>
void update_stock(int x[]); 1 stock[0] 1
2 stock[1] 4
int main()
{ 3 stock[2] 9
int stock[5]={1,2,3,4,5}; Pass only
name of the 4 stock[3] 16
update_stock(stock); array
5 stock[4] 25
} Declare an
array
void update_stock(int x[]) variable
{ without size x is pointing to
int i; x
stock[]
for(i=0;i<5;i++)
printf("%d x %d = %d\n",i,i, x[i]=x[i]*x[i]);
}
*Element in an array can be changed by passing the array name
- Without constant modifier.
14
Example 4 : Passing the whole array for updating
• This program will modify the value of array marks[10] in which all students will get extra 5 marks.
#include <stdio.h>
void student(int x[ ]);
void student(int x[ ])
int main( ) {
{ int i;
int i,marks[10]={1,2,3,6,1,1,1,1}; for( i=0; i<10; i++)
x[i] += 5;
student(marks); }
number(price);
17
Error: Passing the whole array for updating
– using constant modifier
#include <stdio.h>
void update(const int x[]);
int main()
{
Const
int stock[5]={1,2,3,4,5}; declared
update(stock);
} Trying to modify
void update(const int x[]) the elements of
{ the array
int i;
for(i=0;i<5;i++)
printf("%d x %d = %d\n",i,i, x[i]=x[i]*x[i]);
}
error: assignment of read-only location '*(x + (unsigned int)((unsigned int)i * 4u))’ 18
Example 5: Passing the array as constant - The correct way
#include <stdio.h>
float average(const int y[]);
int main()
Constant
{
modifier
int stock[5]={3,7,2,4,5};
declared
float av;
av = average(stock);
printf("Average = %.2f", av);
20
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
21
Declaration and Initialization
• Two-dimensional array declaration
int table[5][4]; Second dimension
First dimension specifies the number
specifies the number of of columns in each
rows in the array row
c) int table[5][4] =
{{0,1},{10},{20,21,22},{30},{40,41,42,43}};
22
Single Dimensional Array vs.
Two-Dimensional Array
Using Array Using 2-Dimensional Array
rows
columns
17 18 19 20 11 12 13
[0,0] [0,1] [0,2]
24 25 26
[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] 23
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}};
printf(“%d”,table[1][2]);// print 12
25
Example 6: Two-Dimensional array
#include <stdio.h>
int main()
{
int i,j,ary1[4][3];
// getting values
for(i=0; i<4; i++){
printf("\nEnter 3 numbers for row %d : ",i+1);
for(j=0; j<3; j++)
scanf("%d",&ary1[i][j]);
} Output :
printf("\nElements of ary1 is : \n"); Enter 3 numbers for row 1 : 1 2 3
Enter 3 numbers for row 2 : 2 4 6
// displaying values Enter 3 numbers for row 3 : 3 6 9
for(i=0; i<4; i++){ Enter 3 numbers for row 4 : 4 8 12
for(j=0; j<3; j++)
printf("%4d", ary1[i][j]); Elements of ary1 is :
printf("\n"); 1 2 3
} 2 4 6
} 3 6 9
4 8 12 26
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
for(r=0;r<5;r++)
for(c=0;c<4;c++)
table[r][c]= r*10 + c ;
27
Two-Dimensional Array :
String
char medicine_name[3][15]= {"101.panadol", "102. claritin","103. methadone"};
28
Passing
two-dimensional
array
29
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
30
Two-Dimensional Array - Example :
Passing an individual element
int main()
{ int i,j,ary1[4][3]={{1,2,3},{2,4,6},{3,6,9},{3,2,1}};
31
Passing the whole array
#include <stdio.h> void display(const int x[4][3])
void display(const int x[4][3]); {
int main() int col,row;
{ for(row=0; row<4; row++)
int {
table[4][3]={{0,1,2},{10,11,12},{20,21,22},{30,31,32}} for(col=0; col<3; col++)
; {
printf("%5d",x[row][col]);
display(table); }
printf("\n"); printf("\n");
Pass the whole
} }
array
}
0 1 2
Display the current
10 11 12 element of the row. Eg:
loop 1 x[0,0] = 0
20 21 22 loop 2 x[0,1] = 1
loop 3 x[0,2] = 2
30 31 32
Test Your Understanding 2
1. Write a Function Call to pass an element of
number[i][j] to a function show.
2. Write Function Prototype of question no. 1.
3. Write a Function Call to pass the whole array grid
to a function show.
4. Write Function Prototype of question no. 3.
33
Lab Exercises
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++) {
printf("%d”, a[i]=a[i]+1); printf(" %d\n",x+1);
} }
• 35
Passing an individual element
Write a program that pass array element
individually from main() to a function().
Then, calculate the sum of array elements
that is divisible by 3. Lastly, display the sum
in main().
int array [ 5 ] ={10, 11, 3, 9, 7};
36
Passing the whole array
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 elements to be
equal to it’s own index number, and the last 10 elements
are equal to three times of it’s own index number.
Output the array in main() so that 10 elements per line
are printed.
37
2-D Array
Write a statement as stated below:
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[][].
38
Find the error
#include <stdio.h>
void print(int a[ ])
void main()
{
int i,j,ary1[3][3]={{1,2,3},{2,4,6},{3,6,9},{3,2,1}};
41
More Lab Exercises
• The reference book, Mc Graw Hill, Third Edition, 2021
• Finding Errors : Page 257; Exercise 6.5.4; No. 1
• Tracing : Page 258; Exercise 6.5.4; No. 2(b)
• Writing C programming: Page 259; Exercise 6.5.4; No. 3
The End