Programming fundamentals 2 Chapter 1: Functions (Sub-Algorithms)

Slides:



Advertisements
Similar presentations
Functions in C++. Functions  Groups a number of program statements into a unit & gives it a name.  Is a complete and independent program.  Divides.
Advertisements

C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Chapter 5 Functions.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 5. Functions.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 3: Functions.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Overview scope - determines when an identifier can be referenced in a program storage class - determines the period of time during which that identifier.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
C++ function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
CPS120: Introduction to Computer Science Decision Making in Programs.
Functions CIS Feb-06. Summary Slide Using Functions Mathematical Functions Misc. Functions Naming Conventions Writing Functions –Function Prototype.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 6 Functions.
#include using namespace std; // Declare a function. void check(int, double, double); int main() { check(1, 2.3, 4.56); check(7, 8.9, 10.11); } void check(int.
GE 211 Dr. Ahmed Telba. // compound assignment operators #include using namespace std; int main () { a =5 int a, b=3; a = b; a+=2; // equivalent to a=a+2.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
Function User defined function is a code segment (block) that perform an specific action. Function Definition: Function Definition: Return_DT F_name (
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Programming Languages -2 C++ Lecture 3 Method Passing Function Recursion Function Overloading Global and Local variables.
Functions Modules in C++ are called functions and classes. Main reason to use functions is : – get aid in conceptual organization.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
User Defined Functions
User-Written Functions
Chapter 6: User-Defined Functions I
-Neelima Singh PGT(CS) KV Sec-3 Rohini
Chapter 7: User-Defined Functions II
REPETITION CONTROL STRUCTURE
Function Topic 4.
Introduction to C++ Systems Programming.
Bill Tucker Austin Community College COSC 1315
Chapter 5 Function Basics
Functions and an Introduction to Recursion
A Lecture for the c++ Course
Chapter 5 Function Basics
Chapter 5 Functions.
User-Defined Functions
Programming fundamentals 2 Chapter 2:Pointer
Programming fundamentals 2 Chapter 2:Function
User-defined Functions
Chapter 9 Scope, Lifetime, and More on Functions
Function User defined function is a code segment (block) that perform an specific action and may return a value. Function Definition: Return_DT F_name.
User Defined Functions
Compound Assignment Operators in C++
Chapter 5 Function Basics
Programming Funamental slides
Function User defined function is a code segment (block) that perform an specific action. Function Definition: Return_DT F_name ( list of formal parameters)
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
User-defined Functions
Group Status Project Status.
Chapter 6 Methods.
Chapter 7: User-Defined Functions II
Chapter 6: User-Defined Functions I
The Function Prototype
Functions and an Introduction to Recursion
Fundamental Programming
Functions Imran Rashid CTO at ManiWeber Technologies.
CS1201: Programming Language 2
Functions Chapter No. 5.
Presentation transcript:

Programming fundamentals 2 Chapter 1: Functions (Sub-Algorithms) Miss:Hanan Hardan

Contents Algorithm Design Sub-Algorithms C++ Functions Definition Types of Functions Examples Function Prototype Scope of Variables Call by Value / Call by Reference

Top-Down Algorithm Design Topics to cover here: Top-Down Design approach Structured Programming Sub-algorithms (a breadth look)

Top-Down Algorithm Design 1) Top-Down Design The problem is divided into its major sub-problems Solve the sub-problems to derive the solution to the original problem. 2) Structured Design: Dividing the problem into smaller sub-problems is called “structured design”, “top-down design”, “step-wise refinement”, and “modular Programming” 3) Structured Programming: The process of implementing a structured design is called “structured programming”

Structured Programming & Structure Chart The main goal of structured programming is to write error-free code to reuse any possible code that has already been written and tested (this is called reusability) to have many sub-problems that are related.

Sub-algorithms A sub-algorithm is a block of instructions that is executed when it is called from some other point of the algorithm. The top-down algorithm design needs - to write the sub-algorithm definitions - to write an algorithm that calls the sub-algorithms (i.e. includes a CALL statement for each one) . Sub-algorithms are of two type: - Sub-algorithms that do not return a value - Sub-algorithms that return a value * The sub-algorithm is called function in C++.

The Sub-algorithm Definition a) Definition of a sub-algorithm that does not return a value 1- Sub-algorithm without arguments: SUBALGORITHM subalgorithm-name ( ) Statements END subalgorithm-name where, ( ) is the empty list.

The Sub-algorithm Definition 2- Sub-algorithm with arguments: SUBALGORITHM subalgorithm-name (parameter-list) Statements END subalgorithm-name where, Parameter-list is a list that contains one or more parameters that are passed to the sub-algorithm.

The Call to a Sub-algorithm The call to a sub-algorithm that does not return a value is given in the CALL statement which has the following syntax: subalgorithm-name (Actual parameters) Examples: draw_circle ( ) sum(4,7) sum(x,y)

The Call to a Sub-algorithm Interpretation of the sub-algorithm call Suppose that algorithm Figure calls the sub-algorithm draw_circle using the call statement CALL draw_circle ( ) Then the flow of control between sub-algorithms will be as follows (see the next diagram): The flow of control in algorithm Figure stops on this statement to initiate the execution of the sub-algorithm draw_circle after this sub-algorithm has finished executing, the next statement in the calling algorithm will be executed.

The Call to a Sub-algorithm Algorithm Figure Sub-algorithm draw_circle ALGORITHM Figure ------- CALL draw_circle ( ) ------ END Figure SUBALGORITHM draw_circle ( ) ------ END draw_circle call return

The Call to a function (C++) program Figure Function draw_circle void main(){ ------- draw_circle ( ); ------ } call void draw_circle ( ) { ------ } return

Example 1: Syntax ( in Algorithm ): Syntax ( in C++ ): SubAlgorithm print_box () output “* * * * * * *\n” output “* “ , 50 , “ * \n” End print_box Algorithm Test begin print_box () output “\n” End Test void print_box () { cout << “* * * * * * *\n” ; cout << “* “ << 50 << “ * \n” ; } void main() print_box (); cout<<endl;

Example 2: Syntax ( in Algorithm ): Syntax ( in C++ ): SubAlgorithm print_box ( n) output “* * * * * * *\n” output “* “ , n , “ * \n” End print_box Algorithm Test Begin Output “ Enter integer number" Input a print_box (a) print_box (5) End Test void print_box (int n) { cout << “* * * * * * *\n” ; cout << “* “ << n << “ * \n” ; } void main() int a; cout<<"\n Enter integer number"; cin>>a; print_box (a); cout<<endl; print_box (5);

The Sub-algorithm Definition b) Definition of a sub-algorithm that returns a value: 1- Sub-algorithm without arguments: ftype SUBALGORITHM subalgorithm-name ( ) Statements END subalgorithm-name Notes: - ftype: is any data type that the result of a subalgortihm can have. If the subalgorithm does not return any result, then no type is specified. -( ) empty list. - If the subalgorithm has a type, then the Statements in the body of the subalgorithm should have return statement, usually it is the last statement.

The Sub-algorithm Definition b) Definition of a sub-algorithm that returns a value: 2- Sub-algorithm without arguments: ftype SUBALGORITHM subalgorithm-name (parameter-list) Statements END subalgorithm-name Notes: - ftype: is any data type that the result of a subalgortihm can have. If the subalgorithm does not return any result, then no type is specified. - parameter-list: includes one or more arguments. - If the subalgorithm has a type, then the Statements in the body of the subalgorithm should have return statement, usually it is the last statement.

The Call to a Sub-algorithm The call to a sub-algorithm that returns a value is given as follows: - The name of the sub-algorithm is given within the OUTPUT statement assignment statement Examples: result  Sum (x, y ) output Sum (x, y )

Example: Syntax ( in Algorithm ): Syntax ( in C++ ): INT SubAlgorithm sum () x5 y7 return x+y End sum Algorithm Test Begin Output “sum=“ ,sum() a  sum() Output “sum=“ , a End Test int sum () { int x=5, y=7 ; return x+y ; } void main() int a; cout<<“sum=“<<sum()<<endl; a=sum(); cout<<“sum=“<<a<<endl;

Example: Syntax ( in Algorithm ): Syntax ( in C++ ): INT SubAlgorithm Rect_area (L, W) a  L * W return a End Rect_area Algorithm Test Begin Output “ Enter 2 integer number" Input a ,b Output “area==“, Rect_area(a,b) z  Rect_area(3,2) Output “area=“ , z End Test int Rect_area (int L, int W) { int a ; a = L * W ; return a ; } void main() int a,b,z; cout<<"\n Enter 2 integer number"; cin>>a>>b; cout<<“area==“<<Rect_area(a,b)<<endl; z=Rect_area(3,2); cout<<“area=“<<z<<endl;

Function - Summary Function Definition: User defined function is a code segment (block) that perform an specific action. Function Syntax: Return_DT F_name ( list of formal parameters) { Action_ body ; }

Types of Functions Function are of 4 types: 1- A function that doesn’t return a value without argument -Return_DT is void -Action_body doesn’t contain return statement. Syntax: void function-name ( ) { local declarations // this is optional executable statements }

Example: function that doesn’t return a value without arguments void print_O ( ) { cout << “ ** “ << endl; cout << “ * * “ << endl; cout << “ ** “ << endl; }

2- A function that doesn’t return a value with arguments Types of Functions 2- A function that doesn’t return a value with arguments -Return_DT is void -Action_body doesn’t contain return statement. Syntax: void function-name(argument_list) { local declarations // this is optional executable statements }

Example: function that doesn’t return a value with arguments void print_box (int n) { cout << “* * * * * * *\n” ; cout << “* “ << n << “ * \n” ; cout << “* * * * * * *\n” ; }

3- A function that returns a result of any type without arguments Types of Functions 3- A function that returns a result of any type without arguments -Return_DT is any type -Action_body contains return statement. Syntax: <any type> function-name( ) { local declarations // this is optional executable statements }

Example: function that return a value without arguments int sum () { int x=5, y=7 ; return x+y ; }

4- A function that returns a result of any type with arguments Types of Functions 4- A function that returns a result of any type with arguments -Return_DT is any type -Action_body contains return statement. Syntax: <any type> function-name(argument_list ) { local declarations // this is optional executable statements }

Example: function that return a value with arguments int Rect_area (int L, int W) { int a ; a = L * W ; return a ; }

Calling (invoking) Function: a) The call to a Function that does not return a value is given in the following syntax: F_name (Actual parameters); e.g. draw_circle ( ); e.g. sum(4,7); b) The call to a Function that returns a value is given as follows: - The name of the functio is given within the output statement e.g cout<<sum(x,y); - The name of the Function is given within the assignment statement e.g. result = sum (x, y );

Example #include <iostream> using namespace std; int Max (int Value1, int Value2) { if (Value1 > Value2) return Value1; else return Value2; } void main() { int a, b; cout<<"\nPlease Enter the values of a and b: "; cin>>a>>b; cout<<"\n the maximum one is: "<<Max(a,b)<<endl; Function Definition Calling the function in an expression like cout<<, condition, assignment statements

Example #include <iostream> using namespace std; int Max (int Value1, int Value2) { if (Value1 > Value2) return Value1; else return Value2; } void main() { int a, b, c; cout<<"\nPlease Enter the values of a and b: "; cin>>a>>b; c=Max(a,b); cout<<"\n the maximum one is: "<<c<<endl;

Example #include <iostream> using namespace std; int Sum (int A, int B) { return (A+B); } void main() { int N1, N2, S; cout<<"\n Please Enter N1 and N2: "; cin>>N1>>N2; S = Sum(N1,N2); cout<<"\nSum= "<<S<<endl;

Example #include <iostream> using namespace std; bool Positive (int Num) { if (Num > 0) return true; else return false; } void main() { int Number; cout<<"\nEnter Number: "; cin>> Number; if (Positive(Number)) cout<<"\n the number is positive"; cout<<"\n the number is negative"; cout<<endl;

Example #include <iostream> using namespace std; float Area (int R) { return (3.14 * R * R ); } void main() { int Radius; cout<<"Enter the Redius: "; cin>>Radius; cout<<"\nCircle Area is: "<<Area(Radius); cout<<endl;

Example #include <iostream> using namespace std; long Power(int Base, int Exp) { int M=1; for(int i=1; i<=Exp; i++) M*=Base; return M; } void main() { int B, E; cout<<"\nEnter Base: "; cin>>B; cout<<"\nEnter Exponent: "; cin>>E; cout<<"\n Result= "<<Power(B,E); cout<<endl;

Example #include <iostream> using namespace std; long Fact (int Num) { int F = 1, i = Num; while (i>=1){ F *= i; i--; } return F; } void main() { int Number; cout<<"Enter an integer number: "; cin>>Number; cout<<endl<<Number<<"!= "<<Fact(Number); cout<<endl;

Example No Return Statement #include <iostream> using namespace std; void Print(char Ch, int n) { for (int i=1; i<=n; i++) cout<<Ch; cout<<endl; } void main() { char Sym; int Number; cout<<"\nEnter the Symbol: "; cin>>Sym; cout<<"\nHow many times: "; cin>>Number; Print(Sym,Number); No Return Statement

Example #include <iostream> using namespace std; int Mul(int V1, int V2) { return V1 * V2; } void Result() { cout<<"\n5 x 9 = "<<Mul(5,9); cout<<"\n4 x 7 = "<<Mul(4,7); cout<<"\n6 x 4 = "<<Mul(6,4)<<endl; } void main() { Result() ; }

The Function Prototype Like other identifiers in C++, function must be declared before it can be referenced. To declare a function, we can insert a function prototype before the main function. The function prototype provides all information that the C++ compiler needs to know to translate calls to the function correctly. A function prototype tells the compiler the - data type of the function - the function name - information about the arguments that the function expects. Examples: void draw_circle ( ); int m ( ) ; void print_box (int) ; int Rect_area (int , int);

Function Prototype #include <iostream.h> int Mul(int, int); int Add(int, int); void Show(); void main() { Show(); } int Mul(int X, int Y) { return X*Y; } int Add(int X, int Y) { return X+Y; } void Show() { int A=10, B=20; cout<<Add(A,B)<<'\t'<<Mul(A,B)<<endl; } Function Prototype contains only data types But may contain identifiers.

Scope of Variables (1) Global variables: - Those variables that are declared before the main function. - These are visible from any point of the code, inside and outside any function. (2) Local variables: - These are declared inside a block or a function. - The scope of local variables is limited to the same nesting level in which they are declared.

Example of Local and Global Variables // File: global.cpp #include <iostream.h> int x = 7 ; // global variables int fun1 (int ); // function prototype void main ( ) { int z ; // local variable in main cout << “The global variable: “ << x ; z = fun1 ( 5 ) ; // calling add function cout << “ The result is “ << z << endl ; } int fun1 ( int a ) { int r ; // local variable in fun1 r = a * a * a ; return r ; }

Example2 of Local and Global Variables #include <iostream> using namespace std; int x = 7; // global variable void main() { int x = 5; cout << "main "<< x<< endl; int x = 3; cout << "in block "<< x<< endl; cout << "global "<< ::x<< endl; } Output: main 5 in block 3 global 7

More about global and local variables When you use the same variable name for both a local and a global variable, the local variable is used in a block or a function instead of the global variable, this operation is called “Masking”. Each variable has a life time, which is the time this variable remains seen by the program. The lifetime of a global variable extends through the execution of the whole program, while the lifetime of a local variable only last until the end of the function or the block where this local variable is defined.

Functions and Passing Parameters The mechanisms of passing parameters: (1) Call by value: - During the function call, the value of the argument is found and passed to the function. - Any modification inside the function does not affect the argument. (2) Call by reference: - During the function call, the address of the variable is passed to the function. - Any modification made on the parameter inside the function will have effect in the passed variable outside it.

Difference between Function Definitions for Call by Value and Call by Reference For call by value, we declare the arguments of the function as usual. Example: int func1 ( int , int ); // function prototype For call by reference, the type of the argument is followed by the symbol (&) to specify that the variable has to be passed by reference. void func2 ( int & , int & ); // function prototype

Call by value When calling, the value of actual parameter will be copied to the formal parameter. #include <iostream.h> void Increment(int); void main() { int A = 10; Increment(A); cout<<A<<endl; } void Increment(int X) { ++X; }

Call By reference When calling, the reference formal parameter will be an alternative name to the actual parameter. #include <iostream.h> void Increment(int&); void main() { int A = 10; Increment(A); cout<<A<<endl; } void Increment(int &X) { ++X; }

Call By reference When calling, the pointer formal parameter will points to the actual parameter. #include <iostream.h> void Increment(int*); void main() { int A = 10; Increment(&A); cout<<A<<endl; } void Increment(int *X) { ++*X; }

Example 1: Call by Value // File: calls1.cpp #include <iostream.h> // function prototype: the arguments to be passed by value int add (int , int ); void main ( ) { int x, y , z ; // local variables in main cout << “ Enter two integers: “ ; cin >> x >> y ; cout << “ x = “ << x << “ y = “ << y << endl; z = add ( x , y ) ; // calling add function cout << “ The result is “ << z ; cout <<“After call “<< “ x = “ << x << “ y = “ << y << endl; } int add ( int a , int b ) { return a + b ; }

Execution of Example 1 The user will be prompted to enter two integers. The user enters, for example, 10 and 20 that are saved in x and y respectively. When function add is called, the value of x and y are passed to the function. The function add takes the values 10 and 20 and links them to a and b respectively. The function will return the result which is 30. The output: Enter two integers: 10 20 x = 10 y = 20 The result is 30 After call x = 10 y = 20

Example 2: Call by Reference // File: calls2.cpp #include <iostream.h> // function prototype: the arguments to be passed by reference void duplicate (int & , int & , int & ); void main ( ) { int x, y , z ; // local variables in main cout << “ Enter three integers: “ ; cin >> x >> y >> z ; cout << “ Before call: “ << “ x = “ << x << “ y = “ << y << “ z = “ << z <<endl; duplicate ( x , y , z ) ; // calling duplicate function cout <<“ After call: << “ x = “ << x << “ y = “ << y << “ z = “ << z <<endl; } void duplicate ( int & a , int & b , int & c ) { a *= 2 ; b *= 2 ; c *= 2 ; }

Execution of Example 2 The user will be prompted to enter three integers. The user enters, for example, 10, 20, and 30 that are saved in x, y, and z respectively. When function duplicate is called, the addresses of x, y, and z are passed to the function. The addresses of x, y, and z are linked to the parameters of the function a, b, and c. The function will duplicate each parameter and save the result in the same parameter. Thus, a becomes 20 hence x becomes 20 also b becomes 40 hence x becomes 40 also c becomes 60 hence x becomes 60 also After the call we see that the values of x, y, and z are changed. The output: Enter three integers: 10 20 30 Before call: x = 10 y = 20 z = 30 After call: x = 20 y = 40 z = 60

Overloading Overloading, is the operation of defining several functions of the same name, but in different signatures. The signature of the function includes, the return data type of the function, the function name, number of parameters passed to it, and the data types of these parameters.

Overloading – Example1 Output: hello # * * * * * integer 2 char & #include <iostream> using namespace std; void print () { cout << "hello" << endl; } void print (char x) cout << x << endl; void print (char a, int b) for (int i=1; i<=b; i++) cout << a<<" "; cout << endl; void print (int x, char y) { cout << "integer " << x<< " char " << y<< endl; } void main() print (); print ('#'); print ('*', 5); print (2, '&'); Output: hello # * * * * * integer 2 char &

Overloading – Example2 Output: Result = 16 Result2 = 30.25 #include <iostream> using namespace std; int square (int x) { return x * x; } float square (float x) void main() { int a = 4, result; float b = 5.5, result2; result = square (a); result2 = square (b); cout<< "Result = "<< result<<endl; cout<< "Result2 = "<< result2<<endl; } Output: Result = 16 Result2 = 30.25

Important Note - Overloading Suppose you have defined these two functions: int max (int x, int y) { if (x > y) return x; else return y; } bool max (int a, int b) if (a > b) return true; return false; In this case the compiler will result this syntax error: Cannot overload functions distinguished by return type alone. This means, that you cannot define the same function name twice or more, with the same number of parameters and the same types, but the only different is the return type. There should be difference in the parameters as well.

Template Assume you have this program: #include <iostream> using namespace std; void swapping (int a, int b) { int temp; temp = a; a = b; b = temp; cout << a << " " << b<< endl; } void swapping (char a, char b) char temp; void main() { swapping (2, 5); swapping ('$', '*'); } Output: 5 2 * $ This is another example of overloading, but you may need to add other functions with other data types as well. In such cases we can define a template function, that we can send to it any data types we need.

Template - Example Output: 5 2 3.66 5.6 * $ Ali Ahmad Assume you have this program: #include <iostream> using namespace std; template <class T> void swapping (T a, T b) { T temp; temp = a; a = b; b = temp; cout << a << " " << b<< endl; } void main() swapping (2, 5); swapping (5.6, 3.66); swapping ('$', '*'); swapping ("Ahmad", "Ali"); Output: 5 2 3.66 5.6 * $ Ali Ahmad In this example, we only needed to define the function swapping once, and we could call it several types using different data types for the parameters.

Template – Example2 #include <iostream> using namespace std; template <class T> T square (T a) { return a * a; } void main() int x = square (2); float y = square (3.5); double z = square (556.98787); long e = square (45268547); cout << "x = "<< x << endl; cout << "y = "<< y << endl; cout << "z = "<< z << endl; cout << "e = "<< e << endl;

Setting default values for parameters in a function Assume you have this program: #include <iostream> using namespace std; void print (char x, char y, char z) { cout << x << " " << y << " "<< z; } void main() print ('@', '$', '%'); Note here that each time you call function print, you will have to send values to the three parameters defined in it. Sometimes, we need to give default values to parameters, so that if the call statement ignored sending them, the default value will be considered.

Setting default values for parameters in a function Assume you have this program: #include <iostream> using namespace std; void print (char x, char y, char z = ‘*’) { cout << x << " " << y << " "<< z; } void main() print ('@', '$', '%'); print ('@', '$'); Output: @ $ % @ $ *

Setting default values for parameters in a function Assume you have this program: #include <iostream> using namespace std; void print (char x, char y = ‘#’, char z = ‘*’) { cout << x << " " << y << " "<< z; } void main() print ('@', '$', '%'); print ('@', '$'); print ('@'); Output: @ $ % @ $ * @ # *

Setting default values for parameters in a function Assume you have this program: #include <iostream> using namespace std; void print (char x = ‘&’, char y = ‘#’, char z = ‘*’) { cout << x << " " << y << " "<< z; } void main() print ('@', '$', '%'); print ('@', '$'); print ('@'); print (); Output: @ $ % @ $ * @ # * & # *

Setting default values for parameters in a function – Example 2 Assume you have this program: #include <iostream> using namespace std; void print (char x , int y =1) { for (int i=1; i<=y; i++) cout << x <<" "; cout << endl; } void main() print ('@', 5); print ('#'); Output: @ @ @ @ @ #

Setting default values for parameters in a function – Example 2 Suppose you have written the function print in the following way: void print (int y =1, char x ) { for (int i=1; i<=y; i++) cout << x <<" "; cout << endl; } Note here, that the first parameter has a default value, while the second doesn’t. C++ will not allow you do order the parameters this way. Always make sure that the parameters with default values are listed at the end of the parameters. This program will result the following syntax error: Default argument not at end of parameter list

Static Variables Consider the following program: #include <iostream> using namespace std; void test () { int x =1; x++; cout << "x = "<< x<< endl; } void main() test(); In the function test, x is defined as a local variable within the function. Its lifetime will extend until the end of the function execution, as was discussed earlier. So, when this program is executed, each time test() is called, x is redefined and initialized with 1, and then incremented. The output in this case will be: x = 2

Static Variables Output: x=2 x=3 x=4 Consider changing a little bit on the program, by specifying the local variable x, as static. #include <iostream> using namespace std; void test () { static int x =1; x++; cout << "x = "<< x<< endl; } void main() test(); Static keyword, that proceeds the declaration of the variable x, will expand its life time. x is still a local variable that can be accessed only within the function test, but its lifetime won’t end by the end of this function. The first time test() is called, x is declared and initialized with 1, and then incremented. The second time test() is called, x, won’t be declared and initialized again, since it is static it has reserved its final value in the previous call, which was 2, so when it is incremented it will become 3. The life time of a static variable, will end when the execution of the whole program is finished. Output: x=2 x=3 x=4

Recursion A Recursive Function, is a function that keeps calling itself until it reaches to its base case (or stopping condition)

Factorial example using loop #include <iostream> using namespace std; void main () { int y, fact =1; cin >> y; for (int i=y; i>=1; i--) fact *=i; cout << fact <<endl; }

Factorial example using Recursion #include <iostream> using namespace std; int Fact (int N) { if (N<=1) return 1; else return N * Fact(N-1); } void main() { cout<<Fact(5)<<endl;

Example 2 #include <iostream> using namespace std; int Fun (int N) { int Z; if (N<=1) Z=1; else Z= Fun(N-1) + Fun(N-3); return Z; } void main() { cout<< Fun(5)<<endl;

Example 3 #include <iostream> using namespace std; void exercise (int x) { if (x > 0 && x < 10) cout << x << " "; exercise (x + 1); } void main () exercise (5);

Example 4 Write a recursive function named, sumSquares, that returns the sum of the squares of the numbers from 0 to num, in which num is a nonnegative int variable.

Example 4: Cont. First, let’s solve this problem using For loop. #include <iostream> using namespace std; void main () { int num, sum = 0; cin >> num; for (int i=num; i>=0; i--) sum = sum + i*i; cout << "Sum = "<< sum << endl; }

Example 4: Cont. Now, solve the problem using recursive function. #include <iostream> using namespace std; int sumSquare (int x) { if (x == 0) return 0; // Base case #1 else if (x == 1) return 1; //Base case #2 return x * x + sumSquare (x-1);} void main () { int num; cin >> num; cout << "Sum = "<< sumSquare(num) << endl; }

Homework Q1: Write a recursive function that finds and returns the sum of the elements in an int array. Write a program to test your function. Q2: Write a recursive function that returns both the smallest and the largest element in an integer array. Write a program to test your function.