Programming: Passing Arrays To Functions

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 10

Programming

Passing
Arrays to
Functions
COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 2

Passing Arrays as Parameters


 Arrays are always passed by reference.
 The “[ ]” in the formal parameter
specification indicates that the variable is
an array.
 It is a good practice to pass the dimension
of the array as another parameter.
 If the function must not change any
element of the array then const should be
used in the formal parameter specification
of that array.
COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 3

Smallest Value
 Problem
 Find the smallest value in a list of integers
 Input
 A list of integers and a value indicating the
number of integers
 Output
 Smallest value in the list
 Note
 List remains unchanged after finding the
smallest value!
COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 4

Passing array to function in C programming

There are three way to implement passing array


to function
 C – Array
 Function call by value in C
 Function call by reference in C
COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 5
COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 6

Passing array to function using call by


value method
 #include <stdio.h>
 void disp( char ch)
 {
 printf("%c ", ch); }
 int main() {
 char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
 for (int x=0; x<10; x++)
 disp (arr[x]);
 }
 return 0;
 }
COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 7

Ouput

abcdefghij
COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 8

Passing array to function using call by


reference

 When we pass the address of an array while


calling a function then this is called function
call by reference. When we pass an address
as an argument, the function declaration
should have a pointer as a parameter to
receive the passed address.
COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 9

Example
1. #include <stdio.h>
2. void disp( int *num)
3. { printf("%d ", *num);
4. }
5. int main()
6. { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
7. for (int i=0; i<10; i++)
8. {
9. disp (&arr[i]);
10. } return 0;
11. }
COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 10

Output

1234567890

You might also like