Introduction to Problem Solving and Programming

Slides:



Advertisements
Similar presentations
1 Lecture 10 Chapter 7 Functions Dale/Weems/Headington.
Advertisements

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
 2007 Pearson Education, Inc. All rights reserved C Functions.
 2007 Pearson Education, Inc. All rights reserved C Functions.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 – Recursive Funtions From Deitel’s “C” Book 5.13Recursion 5.14Example Using Recursion: The Fibonacci.
Chapter 7 Functions.
1 Chapter 7 Functions. 2 Chapter 7 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task l Using Function Arguments.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
1 Programming in C++ Dale/Weems/Headington Chapter 7 Functions.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Lecture 6 – Functions (2). Outline Recall - sample application functions that return no value functions that return a value Recall – global variable vs.
1. Function prototype Function prototype is a declaration; indicates the function exists Should have function name, return type and parameter Placed before.
Write a C program to pass an array containing age of person to a function. This function should find average age and display the average age in main function.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
1 Functions every C++ program must have a function called main program execution always begins with function main any other functions are subprograms and.
Chapter 8 Functions. Chapter 8 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task l Using Function Arguments.
1 Functions. 2 Chapter 7 Topics  Writing a Program Using Functional Decomposition  Writing a Void Function for a Task  Using Function Arguments and.
1 CSE1301 Computer Programming Lecture 12 Functions (Part 1)
UniMAP SemII-09/10EKT120: Computer Programming1 Week 6 – Functions (2)
Chapter 5 – Functions II Outline Recursion Examples Using Recursion: The Fibonacci Series.
1 Chapter 7 Functions Dale/Weems/Headington. 2 Chapter 7 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task.
1 CSE1301 Computer Programming Lecture 13 Functions (Part 1)
Write a C program to pass an array containing age of person to a function. This function should find average age and display the average age in main function.
Functions Programming Applications. Functions every C program must have a function called main program execution always begins with function main any.
1 CSC103: Introduction to Computer and Programming Lecture No 16.
C++ Programming Lecture 12 Functions – Part IV
1 CSE1301 Computer Programming Lecture 12 Functions (Part 1)
Objectives: How to define and call functions. Function declarations and how they differ from function definitions. How arguments are passed to functions.
CS212: Data Structures and Algorithms
Chapter 8 Functions.
Function – I What is a function Why we need functions?
User-Written Functions
Topic 6 Recursion.
Chapter 15 Recursion.
C Functions -Continue…-.
EKT120: Computer Programming
Lesson #6 Modular Programming and Functions.
Lesson #6 Modular Programming and Functions.
C Functions Pepper.
Chapter 15 Recursion.
ICS103 Programming in C Lecture 10: Functions II
Chapter 10: Void Functions
Functions and an Introduction to Recursion
Functions Dr. Sajib Datta
INC 161 , CPE 100 Computer Programming
ARRAYS An array is a sequence of data item of homogeneous value(same type). Arrays are of two types: 1. One-dimensional arrays 2. Multi-Dimensional arrays.
Chapter 5 - Functions Outline 5.1 Introduction
Functions.
Functions Dr. Ashish Sasankar. In programming, a function is a segment that groups code to perform a specific task. A C program has at least one function.
Chapter 5 - Functions Outline 5.1 Introduction
Lesson #6 Modular Programming and Functions.
Chapter 6 - Functions Outline 5.1 Introduction
CSI 121 Structured Programming Language Lecture 13 Functions (Part 1)
Functions Recursion CSCI 230
Outline Defining and using Pointers Operations on pointers
Module 1-10: Recursion.
Lesson #6 Modular Programming and Functions.
Functions and an Introduction to Recursion
Introduction to Problem Solving and Programming
In C Programming Language
CS148 Introduction to Programming II
1-6 Midterm Review.
ICS103 Programming in C Lecture 10: Functions II
Chapter 8 Functions.
Introduction to Computing Lecture 08: Functions (Part I)
ICS103 Programming in C Lecture 11: Recursive Functions
ICS103 Programming in C Lecture 10: Functions II
Presentation transcript:

Introduction to Problem Solving and Programming Lecture 5 – Functions Pass by Value and Pass by Reference Recursion

Outline Differences between Value Parameters and Reference Parameters Recursion

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.

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.

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.

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.

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.

Pass-by-value “incoming” value of argument CALLING BLOCK FUNCTION CALLED

Pass-by-reference OR, “incoming” original value of argument CALLING BLOCK FUNCTION CALLED “outgoing” changed value of argument OR,

Pass-by-reference argument has no value yet when call occurs CALLING BLOCK FUNCTION CALLED “outgoing” new value of argument

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

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

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

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

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

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

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

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

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.

#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 ……..

Function Definition void GetRoots( float a, float b, float c, float *root1, float *root2) { float temp; // local variable temp = b * b - 4.0 * a * c; *root1 = (-b + sqrt(temp) ) / ( 2.0 * a ); *root2 = (-b - sqrt(temp) ) / ( 2.0 * a ); return; }

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.

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

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).

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.

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

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

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.

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: 2 3 4 5 Displaying: 2 3 4 5

Recursion

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.

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

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).

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); }

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

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.

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);

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) =5+4+3+2+sum(1) =5+4+3+2+1+sum(0) =5+4+3+2+1+0 =5+4+3+2+1 =5+4+3+3 =5+4+6 =5+10 =15

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

Writing Recursive C Functions Factorial int factorial(int n) { if (n == 0) return 1 ; else return n * factorial(n-1) ; }

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) + 1 + 1 + 0 = 1 +0 + 1 + 1 + 0 = 3

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)); }

Recursive Functions F(X) = 2 *X + F ( X – 2) ; F(0) = F(1) = 0;

Questions?