Download presentation
Presentation is loading. Please wait.
Published byJustina Charles Modified over 5 years ago
1
Introduction to Problem Solving and Programming
Lecture 5 – Functions Pass by Value and Pass by Reference Recursion
2
Outline Differences between Value Parameters and Reference Parameters
Recursion
5
MAIN PROGRAM MEMORY 25 4000 age If you pass only a copy of 25 to a function, it is called “pass-by-value” and the function will not be able to change the contents of age. It is still 25 when you return.
6
MAIN PROGRAM MEMORY 25 4000 age 40 4000 age BUT, if you pass 4000, the address of age to a function, it is called “pass-by-reference” and the function will be able to change the contents of age. It could be any number (for example 40) when you return.
7
Argument in Calling Block
4000 25 age Value Parameter Reference Parameter The memory address (4000) of the argument is passed to the function when it is called. The value (25) of the argument is passed to the function when it is called.
8
By default, parameters are always value parameters, unless you do something to change that. To get a reference parameter you need to use addresses as parameters.
9
When to Use Reference Parameters
reference parameters should be used when you want your function to give a value to, or change the value of, a variable in the calling block. Return more than one variables.
10
Pass-by-value “incoming” value of argument CALLING BLOCK
FUNCTION CALLED
11
Pass-by-reference OR, “incoming” original value of argument CALLING
BLOCK FUNCTION CALLED “outgoing” changed value of argument OR,
12
Pass-by-reference argument has no value yet when call occurs CALLING
BLOCK FUNCTION CALLED “outgoing” new value of argument
13
Example: bad_swap.c Output: int main() { int a = 3, b = 5;
/* Swap the values of two variables. */ void badSwap ( int a, int b ) { int temp; temp = a; a = b; b = temp; printf("%d %d\n", a, b); } int main() { int a = 3, b = 5; printf("%d %d\n", a, b); badSwap ( a, b ); return 0; } Output: 3 5 13
14
Example: bad_swap.c Output: int main() { int a = 3, b = 5;
/* Swap the values of two variables. */ void badSwap ( int a, int b ) { int temp; temp = a; a = b; b = temp; printf("%d %d\n", a, b); } int main() { int a = 3, b = 5; printf("%d %d\n", a, b); badSwap ( a, b ); return 0; } Output: 3 5 5 3 14
15
Example: bad_swap.c Output: int main() { int a = 3, b = 5;
/* Swap the values of two variables. */ void badSwap ( int a, int b ) { int temp; temp = a; a = b; b = temp; printf("%d %d\n", a, b); } int main() { int a = 3, b = 5; printf("%d %d\n", a, b); badSwap ( a, b ); return 0; } Output: 3 5 5 3 15
16
Example: bad_swap.c Output: int main() { int a = 3, b = 5;
/* Swap the values of two variables. */ void badSwap ( int a, int b ) { int temp; temp = a; a = b; b = temp; printf("%d %d\n", a, b); } int main() { int a = 3, b = 5; printf("%d %d\n", a, b); badSwap ( a, b ); return 0; } Output: 3 5 5 3 16
17
Example: swap.c Output: int main() { int a = 3, b = 5;
/* Swap the values of two variables. */ void Swap ( int *a, int *b ) { int temp; temp = *a; *a = *b; *b = temp; printf("%d %d\n", *a, *b); } int main() { int a = 3, b = 5; printf("%d %d\n", a, b); Swap ( &a, &b ); return 0; } Output: 3 5 17
18
Example: swap.c Output: int main() { int a = 3, b = 5;
/* Swap the values of two variables. */ void Swap ( int *a, int *b ) { int temp; temp = *a; *a = *b; *b = temp; printf("%d %d\n", *a, *b); } int main() { int a = 3, b = 5; printf("%d %d\n", a, b); Swap ( &a, &b ); return 0; } Output: 3 5 5 3 18
19
Example: swap.c Output: int main() { int a = 3, b = 5;
/* Swap the values of two variables. */ void Swap ( int *a, int *b ) { int temp; temp = *a; *a = *b; *b = temp; printf("%d %d\n", *a, *b); } int main() { int a = 3, b = 5; printf("%d %d\n", a, b); Swap ( &a, &b ); return 0; } Output: 3 5 5 3 19
20
Example: swap.c Output: int main() { int a = 3, b = 5;
/* Swap the values of two variables. */ void Swap ( int *a, int *b ) { int temp; temp = *a; *a = *b; *b = temp; printf("%d %d\n", *a, *b); } int main() { int a = 3, b = 5; printf("%d %d\n", a, b); Swap ( &a, &b ); return 0; } Output: 3 5 5 3 20
21
Example of Pass-by-Reference
We want to find 2 real roots for a quadratic equation with coefficients a,b,c. Write a prototype for a void function named GetRoots( ) with 5 parameters. The first 3 parameters are type float. The last 2 are reference parameters of type float.
22
#include <stdio. h> #include <math
#include <stdio.h> #include <math.h> void GetRoots(float, float, float, float*, float*); void main ( ) { float a, b, c, first, second; printf(“ Enter a b c : “); scanf(“%f %f %f”, &a , &b, &c ); GetRoots(a, b, c, &first, &second); printf(“ Roots are %.2f %.2f \n “ , first , second ); } // function GetRoots goes here ……..
23
Function Definition void GetRoots( float a, float b, float c, float *root1, float *root2) { float temp; // local variable temp = b * b * a * c; *root1 = (-b + sqrt(temp) ) / ( 2.0 * a ); *root2 = (-b - sqrt(temp) ) / ( 2.0 * a ); return; }
24
Calling Functions with Arrays
In C programming, a single array element or an entire array can be passed to a function. Also, both one-dimensional and multi- dimensional array can be passed to function as argument.
25
Passing a single element of an array to function
#include <stdio.h> void display(int a) { printf("%d",a);} int main() {int c[]={2,3,4}; display(c[2]); //Passing array element c[2] only. return 0;} Output : 4
26
Passing Entire One-Dimensional Array to a Function
While passing arrays to the argument, the name of the array is passed as an argument (i.e., starting address of memory area is passed as argument).
27
Passing Entire One-Dimensional Array to a Function
Write a C program to pass an array containing age of 6 persons to a function. This function should find average age and display the average age in main function.
28
Passing Entire One-Dimensional Array to a Function
#include <stdio.h> float average(float a[]); int main() { float avg, c[]={23.4, 55, 22.6, 3, 40.5, 18}; avg=average(c);/* Only name of array is passed as argument. */ printf("Average age=%.2f",avg); return 0; } float average(float a[]) {int i;float avg, sum=0.0; for(i=0;i<6;i++) {sum+=a[i];} avg =(sum/6); return avg; Average age=27.08
29
Returning a One-Dimensional Array from a Function
#include <stdio.h> int* test(int size, int x); int main() { int n = 3, a = 10, i; int *z; z = test(n, a); for (i=0; i<10;i++) printf("%d", z[i]); return (0); } int* test(int size, int x) int* factorFunction = malloc(sizeof(int) * size); factorFunction[0] = 5 + x; factorFunction[1] = 7 + x; factorFunction[2] = 9 + x; return (factorFunction); Average age=27.08
30
Passing Multi-dimensional Arrays to Function
To pass two-dimensional array to a function as an argument, starting address of memory area reserved is passed as in one dimensional array.
31
Passing Multi-dimensional Arrays to Function
#include <stdio.h> void Function(int c[2][2]); int main() {int c[2][2],i,j; printf("Enter 4 numbers:\n"); for(i=0;i<2;++i)for(j=0;j<2;++j) {scanf("%d",&c[i][j]);} Function(c); /*passing multi-dimensional array to function */ return 0; } void Function(int c[2][2]) {/* Instead to above line, void Function(int c[][2]){ is also valid */ int i,j; printf("Displaying:\n"); for(i=0;i<2;++i) for(j=0;j<2;++j) printf("%d\n",c[i][j]); Enter 4 numbers: Displaying:
32
Recursion
33
Recursive Functions What is recursion? When one function calls ITSELF directly or indirectly. A function is a recursive if a statement in the body of the function calls the function that contains it.
34
Recursive Functions New mode of thinking. Powerful programming tool.
Why learn recursion? New mode of thinking. Powerful programming tool. Divide-and-conquer paradigm. Many computations are naturally self- referential
35
Recursive Functions (cont.)
A recursive definition is made up of two parts. Base case that tells us directly what the answer is. Recursive case that defines the answer in terms of the answer to a subproblem. For example, in factorial: Base case is factorial(0)=1. Recursive case is factorial(n) = n * factorial(n-1).
36
Recursive Functions Recursive Function Multiply
int multiply ( int m, int n) { int ans; If (n==1) ans=m; else ans= m + multiply (m, n-1); return (ans); }
37
Recursive Functions multiply (6,3) int multiply ( int m, int n)
{ int ans; If (n==1) ans=m; else ans= m + multiply (m, n-1); return (ans); } m is 6 n is 3 3 == 1 is false ans is 6 + multiply (6,2) return (ans) 18 m is 6 n is 2 2 == 1 is false ans is 6 + multiply (6,1) return (ans) 12 m is 6 n is 1 1 == 1 is true ans is 6 return (ans) 6
38
Recursive Functions When a function calls itself, new local variables are allocated storage on the stack, and the function code is executed with these new variables from the beginning . A recursive call does not make a new copy of the function. Only the arguments are new.
39
Recursive Functions – Example
#include <stdio.h> int sum(int n) { if(n==0) return n; else return n+sum(n-1); } int main() { int num,add; printf("Enter a positive integer:\n"); scanf("%d",&num); add=sum(num); printf("sum=%d",add);
40
Recursive Functions – Example
#include <stdio.h> int sum(int n); int main() { int num,add; printf("Enter a positive integer:\n"); scanf("%d",&num); add=sum(num); printf("sum=%d",add); } int sum(int n) { if(n==0) return n; else return n+sum(n-1); sum(5) =5+sum(4) =5+4+sum(3) =5+4+3+sum(2) = sum(1) = sum(0) = = = =5+4+6 =5+10 =15
41
Recursive Functions - Factorial
Functions are very often defined recursively. The classic example is the factorial function. factorial(0) = 1 factorial(n) = n * factorial(n-1) [for n>0] Let's compute factorial(3). factorial(3) = 3 * factorial(2) = 3 * 2 * factorial(1) = 3 * 2 * 1 * factorial(0) = 3 * 2 * 1 * 1 = 6
42
Writing Recursive C Functions Factorial
int factorial(int n) { if (n == 0) return 1 ; else return n * factorial(n-1) ; }
43
Fibonnacci Series 0, 1, 1, 2, 3, 5, 8, 13, 21, … Base Cases:
fib(0) = 0, fib(1) = 1 Recursive Case (two recursive calls): fib(n) = fib(n-1) + fib(n-2) [for n>1] fib(4)= fib(3) + fib(2) = fib(2) + fib(1) + fib(1) + fib(0) = fib(1) + fib (0) = = 3
44
Writing Recursive C Functions Fibonacci
int fib(int n) { if (n == 0) return 0; if (n == 1) return 1; else return (fib(n-1) + fib(n-2)); }
45
Recursive Functions F(X) = 2 *X + F ( X – 2) ; F(0) = F(1) = 0;
46
Questions?
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.