Part 3-functions1-120315220356-phpapp01

23
Functions Name – Tarandeep Kaur Section – N2 Roll No. – 115331

Transcript of Part 3-functions1-120315220356-phpapp01

Page 1: Part 3-functions1-120315220356-phpapp01

FunctionsName – Tarandeep KaurSection – N2Roll No. – 115331

Page 2: Part 3-functions1-120315220356-phpapp01

Definition of functions Function calling Function definition Void function Remarks on function Local v/s Global variables Function call methods Concept of recursion Function overloading

Content

Page 3: Part 3-functions1-120315220356-phpapp01

A function is a subprogram that acts on data and often returns a value.

Definition of functions

Page 4: Part 3-functions1-120315220356-phpapp01

About Functions in C++ Functions invoked by a function–call-statement which

consist of it’s name and information it needs (arguments) Boss To Worker Analogy A Boss (the calling/caller function) asks a worker (the

called function) to perform a task and return result when it is done.

Main

Boss

Function A Function B Function Z

WorkerWorker

Function B2Function B1

Worker

Worker Worker Note: usual main( ) Calls other functions, but other functions

can call each other

Page 5: Part 3-functions1-120315220356-phpapp01

Function Calling

Function Arguments can be:- Constant sqrt(9);- Variable sqrt(x);- Expression sqrt( x*9 + y) ;

sqrt( sqrt(x) ) ;

• Functions called by writingfunctionName (argument);orfunctionName(argument1, argument2, …);

• Examplecout << sqrt( 900.0 );

• sqrt (square root) function • The preceding statement would print 30• All functions in math library return a double

Page 6: Part 3-functions1-120315220356-phpapp01

Function Calling

cout<< sqrt(9);

Function Name argument

3

Output

Parentheses used to enclose argument(s)

• Calling/invoking a function– sqrt(x);– Parentheses an operator used to call function

• Pass argument x• Function gets its own copy of arguments

– After finished, passes back result

Page 7: Part 3-functions1-120315220356-phpapp01

Functions◦ Modularize a program◦ Software reusability

- Call function multiple times Local variables

◦ Known only in the function in which they are defined◦ All variables declared in function definitions are local variables

Parameters◦ Local variables passed to function when called◦ Provide outside information

Functions

Page 8: Part 3-functions1-120315220356-phpapp01

Function prototype◦ Tells compiler argument type and return type of function◦int square( int );

- Function takes an int and returns an int

◦ Explained in more detail later

Calling/invoking a function◦square(x);◦ Parentheses an operator used to call function

- Pass argument x- Function gets its own copy of arguments

◦ After finished, passes back result

Function Definition

Page 9: Part 3-functions1-120315220356-phpapp01

Example functionint square( int y ){ return y * y;}

return keyword◦ Returns data, and control goes to function’s caller

- If no data to return, use return;

◦ Function ends when reaches right brace- Control goes to caller

Functions cannot be defined inside other functions

Function Definition

Page 10: Part 3-functions1-120315220356-phpapp01

// Creating and using a programmer-defined function. #include <iostream.h> int square( int ); // function prototype int main() { // loop 10 times and calculate and output // square of x each time for ( int x = 1; x <= 10; x++ ) cout << square( x ) << " "; // function call cout << endl; return 0; // indicates successful termination } // end main

// square function definition returns square of an integer int square( int y ) // y is a copy of argument to function { return y * y; // returns square of y as an int } // end function square

Definition of square. y is a copy of the argument passed. Returns y * y, or y squared.

Function prototype: specifies data types of arguments and return values. square expects an int, and returns an int.

Parentheses () cause function to be called. When done, it returns the result.

1 4 9 16 25 36 49 64 81 100

Page 11: Part 3-functions1-120315220356-phpapp01

} // end main // function maximum definition. x, y and z are parameters double maximum( double x, double y, double z ) { double max = x; // assume x is largest

if ( y > max ) // if y is larger, max = y; // assign y to max

if ( z > max ) // if z is larger, max = z; // assign z to max return max; // max is largest value

} // end function maximum

// Finding the maximum of three floating-point (real) numbers. #include <iostream.h> double maximum( double, double, double ); // function prototype int main() { double number1, number2; double number3; cout << "Enter three real numbers: "; cin >> number1 >> number2 >> number3; // number1, number2 and number3 are arguments to the maximum function call cout << "Maximum is: " << maximum( number1, number2, number3 ) << endl; return 0; // indicates successful termination

Enter three real numbers: 99.32 37.3 27.1928Maximum is: 99.32

Enter three real numbers: 1.1 3.333 2.22Maximum is: 3.333

Function maximum takes 3 arguments (all double) and returns a double.

Page 12: Part 3-functions1-120315220356-phpapp01

Function prototype contains◦ Function name◦ Parameters (number and data type)◦ Return type (void if returns nothing)◦ Only needed if function definition after function call

Prototype must match function definition◦ Function prototypedouble maximum( double, double, double );

◦ Definitiondouble maximum( double x, double y, double z )

{ …}

Function Prototypes

Page 13: Part 3-functions1-120315220356-phpapp01

void Function takes argumentsIf the Function does not RETURN result, it is called void

Function

#include<iostream.h>

void add2Nums(int,int);main(){ int a, b;

cout<<“enter tow Number:”; cin >>a >> b;

add2Nums(a, b)return 0;

} void add2Nums(int x, int y)

{cout<< x<< “+” << y << “=“ << x+y;

}

Page 14: Part 3-functions1-120315220356-phpapp01

void Function take no argumentsIf the function Does Not Take Arguments specify this with

EMPTY-LIST OR write void inside #include<iostream.h>

void funA();void funB(void)main(){

funA();funB();return 0;

} void funA() {

cout << “Function-A takes no arquments\n”;}void funB(){

cout << “Also Function-B takes No arguments\n”;}

Will be the same in all cases

Page 15: Part 3-functions1-120315220356-phpapp01

Remarks on Functions

Local variables◦ Known only in the function in which they are defined◦ All variables declared inside a function are local variables

Parameters◦Local variables passed to function when called (passing-

parameters) Variables defined outside and before function main:

◦ Called global variables◦Can be accessible and used anywhere in the entire

program

Page 16: Part 3-functions1-120315220356-phpapp01

Local vs Global Variables#include<iostream.h>int x,y; //Global Variablesint add2(int, int); //prototypemain(){ int s;

x = 11;y = 22;cout << “global x=” << x << endl;cout << “Global y=” << y << endl;s = add2(x, y);cout << x << “+” << y << “=“ << s;cout<<endl;cout<<“\n---end of output---\n”;return 0;

}int add2(int x1,int y1){ int x; //local variables

x=44;cout << “\nLocal x=” << x << endl;return x1+y1;

}

global x=11global y=22Local x=4411+22=33---end of output---

Page 17: Part 3-functions1-120315220356-phpapp01

Function Call Methods Call by value

• A copy of the value is passed Call by reference

• The caller passes the address of the value

Call by value Up to this point all the calls we have seen are call-by-value, a copy

of the value (known) is passed from the caller-function to the called-function

Any change to the copy does not affect the original value in the caller function

Advantages, prevents side effect, resulting in reliable software

Page 18: Part 3-functions1-120315220356-phpapp01

Function Call Methods Call By Reference We introduce reference-parameter, to perform call by reference. The caller

gives the called function the ability to directly access the caller’s value, and to modify it.

A reference parameter is an alias for it’s corresponding argument, it is stated in c++ by “flow the parameter’s type” in the function prototype by an ampersand(&) also in the function definition-header.

Advantage: performance issue

void function_name (type &);// prototype

main(){

-----------

}void function_name(type &parameter_name)

Page 19: Part 3-functions1-120315220356-phpapp01

Function Call Example#include<iostream.h>int squareVal(int); //prototype call by value functionvoid squareRef(int &); // prototype call by –reference functionint main(){ int x=2; z=4;

cout<< “x=“ << x << “before calling squareVal”;cout << “\n” << squareVal(x) << “\n”; // call by valuecout<< “x=“ << x << “After returning”cout<< “z=“ << z << “before calling squareRef”;squareRef(z); // call by referencecout<< “z=“ << z<< “After returning squareRef”return 0;

}int squareVal(int a){

return a*=a; // caller’s argument not modified}void squarRef(int &cRef){

cRef *= cRef; // caller’s argument modified}

x=2 before calling squareVal4x=2 after returningz=4 before calling squareRefz=16 after returning squareRef

Page 20: Part 3-functions1-120315220356-phpapp01

Recursion and Recursive Functions

Main calls another function…..normal A function calls another function2….normal A function calls itself ?! Possible?? YESA recursive function is one that call itself.

Page 21: Part 3-functions1-120315220356-phpapp01

Concept Of recursion

A recursive function is called to solve a problem The function knows to solve only the simplest cases

or so-called base-cases Thus if the function called with a base-case, it simply

returns a result. But if it is called with more complex problem, the function divides the problem into two conceptual pieces, one knows how to do, and another doesn't know what to do.

The second case/piece must resemble the original problem, but be a slightly simpler/smaller version of the original problem

Page 22: Part 3-functions1-120315220356-phpapp01

Function overloading◦ Functions with same name and different parameters◦ Should perform similar tasks

- I.e., function to square ints and function to square floatsint square( int x) {return x * x;}

float square(float x) { return x * x; } A call-time c++ complier selects the proper function by

examining the number, type and order of the parameters

Function Overloading

Page 23: Part 3-functions1-120315220356-phpapp01

THANKS