Lecture 6 – Functions (2). Outline Recall - sample application functions that return no value functions that return a value Recall – global variable vs.

Slides:



Advertisements
Similar presentations
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
Advertisements

Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Functions a group of declarations and statements that is assigned a name effectively, a named statement block usually has a value a sub-program when we.
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
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.
Computer Science 210 Computer Organization Introduction to C.
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
Functions Lecture 4 – Section 2: 9/21/05 Section 4: 9/22/05.
CSEB114: PRINCIPLE OF PROGRAMMING Chapter 8: Arrays.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
1. Function prototype Function prototype is a declaration; indicates the function exists Should have function name, return type and parameter Placed before.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions (Recursion) Outline 5.13Recursion 5.14Example.
Principles of Programming - NI Simple Recursion Recursion is where a function calls itself. Concept of recursive function: A recursive function is.
ARRAY Prepared by MMD, Edited by MSY1.  Introduction to arrays  Declaring arrays  Initializing arrays  Examples using arrays  Relationship with pointers.
1 CSC103: Introduction to Computer and Programming Lecture No 14.
 2007 Pearson Education, Inc. All rights reserved C Functions -Continue…-
Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI.
UniMAP SemII-09/10EKT120: Computer Programming1 Week 6 – Functions (2)
Chapter 5 – Functions II Outline Recursion Examples Using Recursion: The Fibonacci Series.
CS140: Intro to CS An Overview of Programming in C by Erin Chambers.
Functions Exercise 5. Functions a group of declarations and statements that is assigned a name  effectively, a named statement block  usually has a.
UniMAP SemI-09/10EKT120: Computer Programming1 Week 5 – Functions (1)
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
Principles of Programming - NI Simple Recursion Recursion is where a function calls itself. Concept of recursive function: A recursive function is.
UniMAP Sem2-09/10 DKT121:Fundamental of Computer Programming1 Functions (2)
Programming Languages -1 (Introduction to C) functions Instructor: M.Fatih AMASYALI
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays.
1 CSC103: Introduction to Computer and Programming Lecture No 16.
A Brief Introduction to Recursion. Recursion Recursive methods … –methods that call themselves! –They can only solve a base case –So, you divide a problem.
C++ Programming Lecture 12 Functions – Part IV
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
1 CSC103: Introduction to Computer and Programming Lecture No 17.
1 Today: Functions. 2 Some General Tips on Programming Write your code modularly Compile + test functionality in the process.
A First Book of ANSI C Fourth Edition
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
Program Development and Design Using C++, Third Edition
Lecture 9 - Pointers 1. Outline Introduction Pointer Variable Definitions and Initialization Pointer Operators Calling Functions by Reference Pointer.
Chapter 9 Recursion. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe recursive function is –a.
UMBC CMSC 104 – Section 01, Fall 2016
User-Written Functions
Topic 6 Recursion.
Chapter 7: User-Defined Functions II
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Week 9 - Pointers.
POINTERS.
C Functions -Continue…-.
EKT120: Computer Programming
Week 6 – Functions (2) PGT C Programming.
POINTERS.
CSC113: Computer Programming (Theory = 03, Lab = 01)
CSC113: Computer Programming (Theory = 03, Lab = 01)
EKT120: Computer Programming
DKT121:Fundamental of Computer Programming
Functions.
Formatted and Unformatted Input/Output Functions
Chapter 5 - Functions Outline 5.1 Introduction
Functions Recursion CSCI 230
Module 1-10: Recursion.
Introduction to Problem Solving and Programming
POINTERS.
1-6 Midterm Review.
ICS103 Programming in C Lecture 11: Recursive Functions
Presentation transcript:

Lecture 6 – Functions (2)

Outline Recall - sample application functions that return no value functions that return a value Recall – global variable vs. local variable Pass by value Functions that “return” more than one value Sample application-functions that “return” more than one value Pass by reference Sample application Recursive function

Sample application Write a C program that reads item code and quantity, then calculate the payment. Use functions: menu – print item code menu determine_price – determine price based on item code calc - calculate payment print_result – print payment Think!! Which function return no value and which function return a value. What argument name do I want to feed in as parameters and what to return??

Sample application-cont #include void menu(); float determine_price(int); float calc(float,int); void print_result(float); int main() {int code,qty; float price,pay; menu(); printf("Enter item code and quantity:"); scanf("%d %d", &code,&qty); price= determine_price(code); pay=calc(price,qty); print_result(pay); return 0; }

Sample application-cont void menu( ) { printf("Code\tItem\tPrice\n"); printf("1\tPapaya\t1.00\n"); printf("2\tMelon\t2.00\n"); printf("3\tDurian\t3.00\n"); printf("\tOthers\t4.00\n"); } float determine_price(int item_code) {float pricing; switch(item_code) { case 1:pricing=1.00;break; case 2:pricing=2.00;break; case 3:pricing=3.00;break; default:pricing=4.00; } return(pricing); } float calc(float item_price,int quantity) {float answer; answer=item_price*quantity; return(answer); } void print_result(float payment) {printf("Payment is %.2f\n", payment); } week5]$ gcc testing.c week5]$./a.out Code Item Price 1 Papaya Melon Durian 3.00 Others 4.00 Enter item code and quantity:1 3 Payment is 3.00 week5]$./a.out Code Item Price 1 Papaya Melon Durian 3.00 Others 4.00 Enter item code and quantity:9 3 Payment is 12.00

Pass by Value If a parameter is passed by value, then the value of the original data is copied into the function’s parameter (scope: local variable(s)) In other words, it (i.e. local variable) has its own copy of the data changes to copy do not change original data During program execution, it (i.e. local variable) will manipulate the data stored in its own memory space

Pass by Value (Example) #include void fun1(int, int); //function prototype int main(void) { int a=5, b=10; printf("Before fun 1\n“); printf(" a = %d b = %d\n”, a, b); fun1(a, b); //function call printf("\nAfter fun 1\n“); printf(" a = %d b = %d\n”, a, b); return 0; } void fun1(int aa, int bb) //function definition { aa++; bb--; printf("\n\nInside fun 1\n)"; printf("aa = %d bb = %d\n”, aa, bb); } Output Before fun 1 a = 5 b = 10 Inside fun 1 aa = 6 bb = 9 After fun 1 a = 5 b = 10

Functions that “return” more than one value When we talk about functions that “return” more than one value it also means that we want to pass arguments by reference pass addresses (references), NOT value/data allows direct manipulation changes will affect original data

Functions that “return” more than one value There are cases where you need to manipulate the value of an external variable from inside a function, thus we pass the values by reference

Comparison Pass by Value Pass by Reference

Sample application Write a C program that calculates and print average of 2 test marks. Your program should have function: read – read 2 test marks calc_avg –calculate average of two test marks print-print average

Sample application #include void read_marks(float*, float*); float calc_avg(float, float); void print(float); int main(void) { float marks1, marks2, avg; read_marks(&marks1, &marks2); avg = calc_avg(marks1, marks2); print(avg); return 0; } void read_marks(float *m1, float *m2) { printf("Enter marks for test1 and test2 : "); scanf("%f %f", m1,m2); //notice no & } float calc_avg(float m1, float m2) { return((m1 + m2)/2); } void print(float average) { printf("\nAverage marks are :%.2f\n",average); } Output Enter marks for test1 and test2 : Average marks are : Functions that “return” more than one value i.e. arguments are pass by reference

Pass by Reference A function’s parameter that receives the location (memory address) of the corresponding actual variables When we attach * (star) after the arg_type in the parameter list of a function, then the variable following that arg_type is passed by reference It stores the address of the actual variable, NOT the value During program execution to manipulate the data, the address stored will direct control to the memory space of the actual variable Syntax In function protoype and function definition, put the * (star) after the data type In function call, put the &(ampersand) before the argument name to be passed by reference

Pass by Reference (cont.) Pass by Reference are useful in two situations: when you want to return more than one value from a function when the value of the actual parameter needs to be changed

Sample application Write a C program that reads character and calculates numbers of vowel and consonant Your program should have function: read – read character find_count_vc –determine and calculate number of vowel or consonant print-print number of vowel or consonant

Sample application #include char read(); void find_count_vc(char, int*, int*); void print(int,int); int main() { char ch, choice; int count_v=0,count_c=0; do { ch = read(); find_count_vc(ch, &count_v, &count_c); printf("Do you want to continue?"); scanf("%c", &choice); }while((choice == 'y') ||(choice =='Y')); print(count_v,count_c); return 0; } char read() { char ch1; printf("Enter character : "); scanf("%c", &ch1); return(ch1); } void find_count_vc(char ch1, int *vowel, int *consonant) { switch(ch1) { case 'A': case 'a': case 'E': case 'e': case 'I': case 'i': case 'O': case 'o': case 'U': case 'u': *vowel = *vowel +1;break; default: *consonant = *consonant + 1; } void print(int vowel, int consonant) { printf("Number of vowel : %d\n", vowel); printf("Number of consonant : %d\n", consonant); } Enter character : f Do you want to continue?y Enter character : I Do you want to continue?y Enter character : k Do you want to continue?n Number of vowel : 1 Number of consonant : 2 Functions that “return” more than one value i.e. arguments are passed by ref

Pass by Reference (Example) #include void fun1(int, int*); //function prototype int main(void) { int a=5, b=10; printf("Before fun 1\n“); printf(" a = %d b = %d“,a, b); fun1(a, &b); //function call printf(“\n\nAfter fun 1\n“); printf("a = %d b = %d\n“,a,b); return 0; } void fun1(int aa, int * bb) //function definition { aa++; *bb--; printf("\n\nInside fun 1\n“); printf("aa = %d bb = %d“,aa,bb); } Output Before fun 1 a=5 b = 10 Inside fun 1 aa = 6 bb = 9 After fun 1 a = 5 b = 9

Recursive Functions Recursion is a term describing functions which are called by themselves (functions that calls themselves) Recursive function has two parts i.e. base case and not base case Recursion can be used to do something repeatedly (similar to loops). For many problems, it is much easier to use recursion than loops to solve the problems. Recursion is very useful in mathematical calculations and in sorting of lists

Recursive Functions (cont.) Example: factorial n! = n * ( n – 1 ) * ( n – 2 ) * … * 1 Recursive relationship: ( n! = n * ( n – 1 )! ) 5! = 5 * 4! 4! = 4 * 3!… Base case (1! = 0! = 1)

Recursive Functions(Example) Factorial Factorial(4) 4 *Factorial(3) 3 *Factorial(2) 2 *Factorial(1) 1 Value 1 is returned 2 * 1 = 2 is returned 3 * 2 = 6 is returned 4 * 6 = 24 is returned

Example #include int Factorial(int n) { if(n <= 1) return 1; else return ( n * Factorial(n-1)); } void main() { int n=4; printf(“Factorial %d is %d“,n, Factorial(n)); }

Example int factorial(int n) // assumes n >= 0 { if (n == 0) return 1; else return n * factorial(n-1); } Note : To see how the computation is done, trace factorial(3): factorial(3) = 3 * factorial(2) = 3 * (2 * factorial(1)) = 3 * (2 * (1 * factorial(0))) = 3 * (2 * (1 * 1))

Example (Recursive Functions in Mathematic) A fibonacci number is the sum of its two previous fibonacci numbers. Given the equation below, The sequence is: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181…

Recursive Functions (Example) Fibonacci series: 0, 1, 1, 2, 3, 5, 8... Each number sum of two previous ones Example of a recursive formula: fib(n) = fib(n-1) + fib(n-2)

Recursive Functions (Example) Diagram of Fibonacci function: f( 3 ) f( 1 ) f( 2 ) f( 1 )f( 0 )return 1 return 0 return + +

Recursive Functions (Example) Sample code for fibonacci function long fibonacci( long n ) { if ( n == 0 || n == 1 ) //base case return n; else return fibonacci( n - 1 ) + fibonacci( n – 2 ); }

Self Exercise: Try this The code is correct, and you can put into your text editor (without the line numbers), save the document as a plain text file, let’s say “fib.c” and then open Terminal and type: gcc fib.c -o fib, and then you’ve compiled a program to be run in Terminal. fib.c was the source code, fib is the program name. You run it by typing./fib 20 which outputs the twentieth fibonacci number. Be aware, at about./fib 40 it begins taking several seconds. You can always abort it by pressing ctrl+c, if you chose a demanding number.

End Lecture 6 – Functions (2) Q & A!