# Functions - PowerPoint PPT Presentation

1 / 75

Functions. Outlines. Advantage of Functions (divide and conquer) Standard Library Functions (Pre-defined functions ) Programmer (User) Defined Functions Local and Global Variables Scope of Variables Functions with no types (void functions) Arrays and Functions

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

Functions

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

## Functions

### Outlines

• Advantage of Functions (divide and conquer)

• Standard Library Functions (Pre-defined functions )

• Programmer (User) Defined Functions

• Local and Global Variables

• Scope of Variables

• Functions with no types (void functions)

• Arrays and Functions

• Arguments passing by value and by reference

• Default values in arguments

• Recursion

• Prototyping function

### Introduction

• Most useful programs are much larger than the programs that we have considered so far

• To make large programs manageable, programmers modularize them into subprograms.

• These subprograms are called functions.

• They can be compiled and tested separately and reused in different programs

• Rather than code one long program, write several smaller routines, called functions. One of those functions must be called main(). The main() function is always the first to execute. It doesn’t have to be first in a program

### Functions

• The best way to develop and maintain large program is to construct from small, simple pieces or components

• The technique is called modular programming or divide and conquer

• Helps to write modular program

• A modular program can be easily understood by the reader of the programs and hence easy to debug, trace and fix

• Functions can be reused in different programs which helps to minimize errors in a program as the functions reused are well tested by other programmers

### Functions

• General Form/Syntax

Ret_Typefunction_Name(Parameter_list)

{

//body of the function

}

• Ret_Type: specifies the data type to be returned by the function

• function_Name: valid identifier name

Alphabet|Underscore + Digit + …

• Parameter_list: comma separated list of variables

• The parenthesis () are required even if the parameter list is empty

### Cont’d…

• Example:

• int a, b, c; // Three variables of type int

• float add; // a floating point variable

• int add( int a, int b); // function with two parameters

• float mult( float x, y); // incorrect funtion declaration, why?

• double balance(); // empty parameter list

• return type is double

• void print(); // does not return a value to the caller

### Two type of functions

• Standard library functions

• Predefined functions

• User defined functions

• The most common once

• Defined by the programmer or user

### STANDARD C++ LIBRARY FUNCTIONS

• Also called built-in functions or predefined functions as they are brought with the C++ compiler

• Functions defined in math.h

• sqrt(), pow(x,y), log10(x), log(x), abs(x), sin(t), cos(t), …

• Functions defined in conio.h

• clrscr(), getch()

• Functions defined in stdlib.h

• rand(),

• Functions defined in string.h

• Strcpy(s1,s2), strcmp(s1,s2), strlen(str)

### (Library functions) Cont’d…

• An example of functions belonging to math.h, stdlib.h, conio.h, iostream.h

// LibFunc.cpp, an example

#include<iostream.h>

#include<math.h>

#include<stdlib.h>

#include<conio.h>

#include<iomanip.h>

### // LibFunc.cpp, an example Cont’d…

void main()

{

for(int x=0;x<=10; x++)

cout<<"\n sqrt{"<<x<<") = "<<sqrt(x);

int a=3, b=-4;

b = abs(b);

cout<<"\n b = "<<b;

cout<<"\n pow(a, b)="<<pow(a,b);

cout<<"\n log(2.71828)= "<<log(2.71828);

cout<<endl;

for(inti=0;i<15; i++)

cout<<(rand() % 15 + 1)<<setw(5);

cout<<endl;

cout<<endl;

for(inti=0;i<10; i++)

cout<<(rand() % 10)<<"\t";

cout<<endl;

for(inti=0;i<10; i++)

cout<<(rand() % 10)<<"\t";

cout<<endl;

for(inti=0;i<10; i++)

cout<<(rand() % 10)<<"\t";

getch();

}

### Cont’d…

Output of LibFunc.cpp

sqrt{0) = 0

sqrt{1) = 1

sqrt{2) = 1.41421

sqrt{3) = 1.73205

sqrt{4) = 2

sqrt{5) = 2.23607

sqrt{6) = 2.44949

sqrt{7) = 2.64575

sqrt{8) = 2.82843

sqrt{9) = 3

sqrt{10) = 3.16228

b = 4

pow(a, b)=81

log(2.71828)= 0.999999

2 11 3 11 2 8 1 11 14 2 5 9 2 5 13

0 2 1 3 7 9 1 0 5 4

9 2 1 9 6 1 1 5 3 4

0 9 5 1 2 9 8 6 4 2

### USER-DEFINED FUNCTIONS

• Programmers also need to be able to define their own functions

• C++ functions generally adhere to the following rules

• Every function must have a name

• Function names are variable names and can contain up to 32 characters, they must begin with a letter, and they can consist of letters, numbers, and the underscore (_) character

• All function names have one set of parentheses immediately following them, which helps to differentiate them from variables.

• Ex: void print() , int cube(x)

### Cont’d…

• The body of each function, starting immediately after the closing parenthesis of the function name, must be enclosed by braces

• Recommended that

• One better use meaningful function names. Calc_balance() is more descriptive than xy3().

Syntax:

Return_TypeFunction_Name(Parameter List)

{

// body of the function

}

### User Defined Functions….

//cube.cpp

#include<iostream.h>

#include<conio.h>

int cube(int x)

{ // returns cube of x:

return x*x*x;

}

void main ()

{

int a;

cout<<"\n Enter a number to find its cube: ";

cin>>a;

cout<<endl;

cout<<a<<" cubed = "<<cube(a)<<endl;

cout<<endl;

for(inti=1;i<=5;i++)

cout<<i<<" cubed = "<<cube(i)<<endl;

getch();

}

Main()

cube()

5

a

int

x

int

5

5

125

void main( )

int a

cube ( a )

Argument passing

int cube(x)

Function call

Return type

### Function, Example: Circle.cpp

Sample Run

Area = 314.159

Circumference = 62.8318

#include<iostream.h>

#include<conio.h>

const float pi = 3.14159;

float area(float x)

{

return pi*x*x;

}

float circumference(float x)

{

return 2*pi*x;

}

void main ()

{

float r;

cin>>r;

cout<<"\n Area = "<<area(r);

cout<<"\n Circumference = "<<circumference(r);

getch();

}

### Cont’d…

#include<iostream.h>

#include<conio.h>

const float rate = 0.08;

float balance(float x)

{

float bal = x + x*rate;

return bal;

}

void main ()

{

float amount;

cout<<"\n Enter the amount: ";

cin>>amount;

cout<<"\n Balance = "<<balance(amount);

getch();

}

### Cont’d…

• Exercise

• Temperature conversion from degree Celsius to degree Fahrenheit and vice-versa is as shown below

• T oC = (T oF - 32 ) * 5/9

• T oF = T oC *9/5 + 32

• Write a function that converts temperature from degree Celsius to degree Fahrenheit

• Write a function that converts temperature from degree Fahrenheit to degree Celsius

### User Defined Functions…

• Assignment(10%)

• Write a function that returns

• Maximum of three floating point numbers

• Minimum of three floating point numbers

• Write a program that uses two functions area and perimeter to find area and perimeter of a rectangle

• Area = x * y

• Perimeter = 2*x*y, where x and y are length and width of the rectangle

• Write a program that calculates net salary for a given basic salary by deducting pension and income tax assume the following:

• Pension: 6% of basic salary and income tax based on the following rule

### Cont’d…

Use separate functions to calculate income tax and pension, use the following format if you wish:

float incomeTax(float basicSal)

{

…….

}

float pension(float basicSal)

{

}

### Function declaration, Function Definition & Function Call

Function Declaration/ Prototype

#include<iostream.h>

#include<conio.h>

void calc_it(int);

int main()

{

calc_it(8);

getch();

return 0;

}

void calc_it(int x)

{

intsqr;

do{

sqr=x * x;

cout<<"\n The square of "<<x<<"="<<sqr;

x++;

}while(sqr<=250);

}

Function Calls

Function Definition

#include<iostream.h>

#include<conio.h>

void compSc()

{

cout<<"\n Welcome to the Computer Science Dept!";

cout<<"\n An ever growing field of study.";

}

void Acct()

{

cout<<"\n Welcome to the Accounting Dept!";

}

void Mgt()

{

cout<<"\n Welcome to the Management Dept!";

}

### Cont’d…

void main()

{

int opt;

do

{

cout<<"\n Computer Science... 1";

cout<<"\n Accounting ........ 2";

cout<<"\n Management ........ 3";

cout<<"\n Quit program....... 4\n";

cout<<"\n Enter your option to view a report: ";

cin>>opt;

switch(opt)

{

case 1:

compSc();

break;

case 2:

Acct();

break;

case 3:

Mgt();

break;

case 4:

cout<<"\n End of the program!!";

break;

}

}while(opt !=4);

getch();

}

### String Functions

//stringFunc1.cpp

#include <iostream.h>

#include <conio.h>

#include <stdio.h>

int main()

{

char str[80];

gets(str);

cout<<"\n Length is: "<<strlen(str);

cout<<endl;

char ch[100];

cin.getline(ch, 100,'#');

cout<<ch;

cout<<"\n Length is: "<<strlen(ch);

getch();

}

### String Functions

#include <iostream.h>

#include <conio.h>

#include <ctype.h>

char* strFunc(char *c)

{

int n = strlen(c);

for(inti=0; i<n; i++)

if(islower(c[i]))

c[i]=toupper(c[i]);

return c;

}

void main()

{

char *ch="Hello World";

cout<<ch;

cout<<endl;

char *p = strFunc(ch);

cout<<p;

getch();

}

### Local and Global variables

• A variable is global if it is defined outside of a function

• A variable is local if it is defined in the body of a function

• A local variable is simply a variable that is declared inside a block. It is accessible only from within that block.

• Since the body of a function itself is a block, variables declared within a function are local to that function; they exist only while the function is executing

• Use global variables only sparingly and when only necessary as they can be illegally modified by someone and introduce undesired effect to the program

### Global vs Local variables

#include<iostream.h>

#include<conio.h>

const float pi = 3.14159; // Global variable

double d; // Global variable

float area(float x)

{

return pi*x*x;

}

float circumference(float y)

{

return 2*pi*y;

}

void main ()

{

float r; // local variable

cin>>r;

cout<<"\n Area = "<<area(r);

cout<<"\n Circumference = "<<circumference(r);

d=2*r;

cout<<"\n Diameter of the circle = "<<d;

getch();

}

x is local to the function area()

y is local to the function circumference()

r is local to the function main()

### Global vs Local variables

Q1. Find and list global and local variables in the program

Q2. Modify the program to appropriate local variables and function using parameters

Illegal modification of salary

#include<iostream.h>

#include<conio.h>

float salary;

float tax()

{

salary = salary-200;

float t = salary * 0.15;

return t;

}

float pension()

{

float p = salary*0.06;

return p;

}

void main ()

{

salary = 1500;

float tx=tax();

float pen =pension();

cout<<"\n Tax = "<<tx;

cout<<"\n Pension = "<<pen;

getch();

}

This program shows not only bad use of global variables but also the importance of using local variables

### Scope of variables

• Scope of variable refers to the function or block in which a variable is accessible or visible

• Variable scope protects variables in one function from other functions that might overwrite them

• If a function doesn’t need access to a variable, that function shouldn’t be able to see or change the variable

• All local variables disappear (lose their definition) when their block ends

• Global variables are visible (“known”) from their point of definition to the end of the program

• A local variable defined in a block is known only in that block

### Global Variables

• Global variables have global scope while local variables have local scope

// Program that contains two global variables.

#include <iostream.h>

#include <conio.h>

do_fun();

third_fun();

main()

{

cout <<"No variables defined in main() \n\n";

do_fun(); // Call the first function

getch();

return 0;

}

Prototype of functions to be discussed later.

### Cont’d…

float sales, profit; // Two global variables.

do_fun()

{

sales = 20000.00;

profit = 5000.00; // .

cout <<"The sales in the second function are " <<sales <<"\n";

cout <<"The profit in the second function is " <<profit <<"\n\n";

third_fun(); // Call the third function to show that global variables are visible.

return 0;

}

third_fun()

{

cout <<"In the third function: \n";

cout <<"The sales in the third function are " <<sales <<"\n";

cout <<"The profit in the third function is " <<profit <<"\n";

// If sales and profit were local, they would not be

// visible by more than one function.

return 0;

}

### Scope of variables

Discuss the scope of each of the variables in the program

#include<iostream.h>

#include<conio.h>

long fact(int n)

{

// returns n! = n*(n-1)*(n-2)*...*(2)(1)

if (n < 0)

return 0;

else if(n == 0 || n ==1)

return 1;

long f = 1;

while (n > 1)

f *= n--;

return f;

}

int main()

{

// tests the factorial() function:

inti;

for (i=-1; i < 6; i++)

cout << " " << fact(i);

getch();

return 0;

}

### Cont’d…

Find out the errors and correct with appropriate local variables

Global Variables

#include<iostream.h>

#include<conio.h>

float rate = 0.05;

intmyVar = 10;

float balance(float x)

{

float b = x - x*rate;

y = 2*y + myVar;

amount = 3*amount;

return b;

}

int y =30;

void main ()

{

myVar = 2*myVar + 5;

cout<<"\n myVar = "<<myVar;

float amount =2200;

cout<<"\n Balance = "<<balance(amount);

b = 5*b+ 100;

getch();

}

### Scope of variables

• Declare all global variables at the top of your program

• Local variables are visible and exist only on their block

#include<iostream.h>

#include<conio.h>

int x=20;

int main()

{

int x=5;

cout<<" x = "<<x<<endl;

{

int x=10;

cout<<" x = "<<x<<endl;

cout<<" ::x = "<<::x<<endl;

}

cout<<" x = "<<x<<endl;

cout<<" ::x = "<<::x<<endl;

getch();

return 0;

}

Scope Resolution operator

### Automatic versus Static variables

• The terms automatic and static describes what happens to local variables when a function returns to the calling procedure

• By default all local variables are automatic i.e. they are erased when their function ends

• You can designate a variable as automatic by prefixing its definition with the term auto which is optional

• Example

main()

{

inti;

auto float x;

}

Both of the variables are automatic variables

### Automatic vs Static variables

Output

The number 1 multiplied by 3 is 3

Total = 3

The number 2 multiplied by 3 is 6

Total = 6

The number 3 multiplied by 3 is 9

Total = 9

The number 4 multiplied by 3 is 12

Total = 12

The number 5 multiplied by 3 is 15

Total = 15

The number 6 multiplied by 3 is 18

Total = 18

The number 7 multiplied by 3 is 21

Total = 21

The number 8 multiplied by 3 is 24

Total = 24

The number 9 multiplied by 3 is 27

Total = 27

The number 10 multiplied by 3 is 30

Total = 30

#include<iostream.h>

#include<conio.h>

triple_it(int ); // function prototype

void main()

{

for(intctr=1; ctr<=10; ctr++)

triple_it(ctr);

getch();

}

triple_it(int c)

{

int total =0, ans;

ans = c*3;

total +=ans;

cout<<"\n The number "<<c<<" multiplied by 3 is "<<ans;

cout<<"\n Total = "<<total;

return 0;

}

### Static variables

• Static variables are variables that retain their values until the end of the entire program

• Declaration proceeded with the static keyword

• By default all global variables are static

void main()

{

int a = 15;

static x = 25;

static y = 30;

}

Automatic variable

Static variables

### Automatic vs Static variables

#include<iostream.h>

#include<conio.h>

void f()

{

static int x=2;

int y =5;

x = 2*x;

y = 3*y;

cout<<"x = "<<x<<endl;

cout<<"y = "<<y<<endl;

}

int main()

{

for(inti = 0; i<3; i++)

f();

getch();

return 0;

}

Output

x = 4

y = 15

x = 8

y = 15

x = 16

y = 15

### Static variable…

#include<iostream.h>

#include<conio.h>

triple_it(int );

void main()

{

for(intctr=1;ctr<=10; ctr++)

triple_it(ctr);

getch();

}

triple_it(int c)

{

static int total =0;

intans;

ans = c*3;

total +=ans;

cout<<"\n The number "<<c<<" multiplied by 3 is "<<ans;

cout<<"\n Total = "<<total;

return 0;

}

• Output next slide

### Cont’d…

The number 1 multiplied by 3 is 3

Total = 3

The number 2 multiplied by 3 is 6

Total = 9

The number 3 multiplied by 3 is 9

Total = 18

The number 4 multiplied by 3 is 12

Total = 30

The number 5 multiplied by 3 is 15

Total = 45

The number 6 multiplied by 3 is 18

Total = 63

The number 7 multiplied by 3 is 21

Total = 84

The number 8 multiplied by 3 is 24

Total = 108

The number 9 multiplied by 3 is 27

Total = 135

The number 10 multiplied by 3 is 30

Total = 165

• Output

### Cont’d…

Give the output here

• Global variables are static

#include<iostream.h>

#include<conio.h>

int total =0;

triple_it(int );

void main()

{

for(intctr=1;ctr<=10; ctr++)

triple_it(ctr);

getch();

}

triple_it(int c)

{

intans;

ans = c*3;

total +=ans;

cout<<"\n The number "<<c<<" multiplied by 3 is "<<ans;

cout<<"\n Total = "<<total;

return 0;

}

### Functions with no types (void functions)

• Functions with no return types are known as void functions

• Does not return value to the caller function

• Example

#include<iostream.h>

#include<conio.h>

int sum(int);

void print(int);

void main()

{

int a=10;

print(a);

}

void function

int sum(int x)

{

int s=0;

for(inti=1;i<=x;i++)

s +=i;

return s;

}

void print(int n)

{

cout<<"The sum is: "<<sum(n);

}

### Arrays and Functions

• When an array is admitted as parameter its type, identifier and pair of square brackets required

• An array is passed as a reference (its address) not by value

• Argument passing by value & reference is to be discussed later

• Example: Write a function that receives an array and doubles each element of the array.

void doubleArray(float arr[ ], int n);

float myArray[] = {1.1, 3.3, 5.5, 7.7, 9.9};

doubleArray(myArray, size);

Function Declaration/Prototype

Function Call

The size of the array

Call to the function doubleArray()

Aarray passing as an argument

### Passing arrays to a function…

#include<iostream.h>

#include<conio.h>

void doubleArray(float arr[], int n)

{

for(inti=0; i<n; i++)

arr[i] = 2*arr[i];

}

void main()

{

float myArray[] = {1.1, 3.3, 5.5, 7.7, 9.9};

int size =sizeof(myArray)/sizeof(float);

doubleArray(myArray, size);

for(inti=0;i<size;i++)

cout<<myArray[i]<<'\t';

getch();

}

Output

2.2 6.6 11 15.4 19.8

### Passing arrays to a function…

• Exercise:

• Write a function that takes an array and its size as arguments and returns the sum of elements of the array

### Passing arrays to a function…

#include<iostream.h>

#include<conio.h>

int sum(int[], int); // prototype of the function

void main()

{

int a[] = { 11,33, 55,77 };

int size = sizeof(a)/sizeof(int);

cout<<"sum(a,size) = " << sum(a,size) << endl;

getch();

}

int sum(int a[],int n)

{

int result=0;

for (inti=0; i<n; i++)

result += a[i];

return result;

}

### Cont’d…

• Exercise

• Write a function that reverses elements of a given array

• Write a function which finds a specific element in a given array and returns the index of the element if it is found

• Write a function which finds the maximum element from a given array and returns the index of the element if it is found

• Write a function which finds the minimum element from a given array and returns the index of the element if it is found

### Passing by Value (by Copy)

• The two wordings “passing by value” and “passing by copy” mean the same thing in computer terms

• When an argument (local variable) is passed by value, a copy of the variable’s value is sent to—and is assigned to—the receiving function’s parameter

• If an expression is used in a function call to pass as a parameter, first the expression is evaluated and the value is passed to the local variable

• The default method for passing parameters is by value, as just described, unless you pass arrays.

• Arrays are always passed by the other method, by address to be discussed later

### Pass by Value/Copy

4

Main

Main

Cube(x)

Cube(x)

#include<iostream.h>

#include<conio.h>

int cube(int x)

{

x = x*x*x;

return x;

}

void main ()

{

int a = 4;

cout<<cube(a)<<endl;

cout<<cube(2*a-3)<<endl;

cout<<“a = “<<a<<endl;

getch();

}

Cube(a)

Cube(a)

x=4*4*4

x=5*5*5

4

5

2*4-3=5

Output

64

125

a = 4

### Cont’d…

• When a variable is passed by value it is read only as seen by the example

• This read only property is almost the usual case and required to protect illegal modification of the variable

• But in some special cases we may need the variable passed to be modified in the called function

• In such a case we use variable pass by reference

• In some situations functions may need to change the value of the parameter passed to it.

• That can be done by passing it by reference

• To pass a parameter by reference instead of by value, simply append an ampersand, &, to the type specified in the functions parameter list

• This makes the local variable a reference to the argument passed to it

• So the argument is read-write

### Cont’d…

• Consider the following function

#include<iostream.h>

#include<conio.h>

void swap(float x, float y)

{

float temp = x;

x = y;

y = temp;

cout<<"Inside swap \n";

cout<<" x = "<<x<<", y = "<<y<<endl;

}

void main ()

{

float a = 4, b = 7;

cout<<"Before swap \n";

cout<<" a = "<<a<<", b = "<<b<<endl;

swap(a,b);

cout<<"After swap \n";

cout<<" a = "<<a<<", b = "<<b<<endl;

getch();

}

Output

Before swap

a = 4, b = 7

Inside swap

x = 7, y = 4

After swap

a = 4, b = 7

### Cont’d…

Reference

swap()

main()

• Write a function that interchanges the value of two variables

#include<iostream.h>

#include<conio.h>

void swap(float& x, float& y)

{

float temp = x;

x = y;

y = temp;

cout<<"Inside swap \n";

cout<<" x = "<<x<<", y = "<<y<<endl;

}

void main ()

{

float a = 4, b = 7;

cout<<"Before swap \n";

cout<<" a = "<<a<<", b = "<<b<<endl;

swap(a,b);

cout<<"After swap \n";

cout<<" a = "<<a<<", b = "<<b<<endl;

getch();

}

x

a

4

y

b

7

Output

Before swap

a = 4, b = 7

Inside swap

x = 7, y = 4

After swap

a = 7, b = 4

### Argument passing by Value and Reference

• In the following function the first argument is passed by value and the second argument is passed by reference. Check the difference

#include<iostream.h>

#include<conio.h>

void f(int x, int& y)

{

x = 3*x;

y=2*y + 5;

cout<<" x = "<<x<<" y = "<<y<<endl;

}

void main()

{

int a = 4, b = 10;

cout<<" a = "<<a<<" b = "<<b<<endl;

f(a,b);

cout<<" a = "<<a<<" b = "<<b<<endl;

getch();

}

Output

a = 4 b = 10

x = 12 y = 25

a = 4 b = 25

### Argument pass by Reference

• What is the use of the return keyword?

• It has two main purposes

• Usually it is used to return a value to the caller function

• Its other use is to terminate the function where the keyword is used

• The return keyword can return only one value to the caller function

• Argument passing by reference or address could be used when there is a need to return more than one value

### The return keyword

Sample Run

Enter two integers: 4 5

4/5 = 0.8

• Using the return Statement to Terminate a Program

#include <iostream.h>

#include <conio.h>

void main()

{ // prints the quotient of two input integers:

float n,d;

cout << "Enter two integers: ";

cin >> n >> d;

if (d == 0) return;

cout << n << "/" << d << " = " << n/d << endl;

getch();

}

The program terminates

### Argument Pass by Reference

//Using argument passing by reference to return more than one value

#include <iostream.h>

#include <conio.h>

const float PI=3.14159;

void computeCircle(float &a, float &c, float r)

{

a=PI*r*r;

c=2*PI*r;

}

void main()

{

float area, circumf, r=10;

computeCircle(area,circumf,r);

cout<<"\n area = "<<area<<" circumference = "<<circumf;

getch();

}

### Cont’d…

• Arrays are always passed by reference by default

include<iostream.h>

#include<conio.h>

void func1(int x, int y)

{

x = 3*x;

y = 3*y;

cout<<" x = "<<x<<" y = "<<y<<endl;

}

void func2(int& x, int& y)

{

x = 3*x;

y = 3*y;

cout<<" x = "<<x<<" y = "<<y<<endl;

}

void func3(int arr[], int n)

{

for(inti=0;i<n;i++)

arr[i] = 3*arr[i];

}

### Cont’d…

Output

a = 5, b = 7

x = 15 y = 21

After call to func1()

a = 5, b = 7

x = 15 y = 21

After call to func2()

a = 15, b = 21

Array elements after call to func3()

3 9 15 21

void main()

{

int a = 5, b = 7;

cout<<" a = "<<a<<", b = "<<b<<endl;

func1(a,b);

cout<<"After call to func1()"<<endl;

cout<<" a = "<<a<<", b = "<<b<<endl;

func2(a,b);

cout<<"After call to func2()"<<endl;

cout<<" a = "<<a<<", b = "<<b<<endl;

int array[] = {1,3,5,7};

func3(array,4);

cout<<"\n Array elements after call to func3()\n";

for(inti=0;i<4;i++)

cout<<array[i]<<" ";

getch();

}

### Default values in arguments

• When declaring a function we can specify a default value for each parameter.

• This value will be used if that parameter is left blank when calling to the function

• //defaultVal.cpp

#include<iostream.h>

#include<conio.h>

void funct1(inti=10, float x=7.5, char c='A‘)

{

cout<<"i = "<<i<<endl;

cout<<"x = "<<x<<endl;

cout<<"c = "<<c<<endl;

}

Default values

Output

i = 10

x = 7.5

c = A

i = 15

x = 7.5

c = A

i = 15

x = 20.45

c = A

i = 15

x = 20.45

c = H

//defaultVal.cpp

void main()

{

int a=15;

float b=20.45;

char ch='H';

funct1();

cout<<endl;

funct1(a);

cout<<endl;

funct1(a,b);

cout<<endl;

funct1(a,b,ch);

getch();

}

### Cont’d…

• Parameters with default values should be to the right of parameters with no default values if there in the parameter list as shown below

// default values in functions

#include <iostream.h>

#include <conio.h>

int divide (int a, int b=2)

{

int r;

r=a/b;

return (r);

}

int main ()

{

cout << divide (12);

cout << endl;

cout << divide (20,4);

getch();

return 0;

}

Output

6

5

### Cont’d…

• Exercise

• Find out what is wrong in the following program to have default values in arguments

• Correct and run the program

#include <iostream.h>

#include <conio.h>

int Calculate(int a=5, int b)

{

return a + b;

}

void main()

{

int x=10, y=15;

cout<<Calculate(y)<<endl;

cout<<Calculate(x,y)<<endl;

getch();

}

### Cont’d…

• What is wrong with the following declarations?

• void add(int a=5, int b, int c=10);

• float average(float a=35, float b=80, float c, float d);

• It is possible to have more than one function with the same name in a program provided that the functions differ either in their return type, data types in the parameter list, or number of parameters in the list

• Function with the same name in the same program are called overloaded functions

• For example the following functions are overloaded

int min(int, int);

int min(int, int, int);

float min(float, float, float);

float min(float, float, float, float);

### Cont’d…

• Consider the following overloaded functions

#include <iostream.h>

#include <conio.h>

int divide (int a, int b)

{

return (a/b);

}

float divide (float a, float b)

{

return (a/b);

}

void main ()

{

intx=5,y=2;

float n=5, m=2;

cout<< divide (x,y);

cout<< "\n";

cout<< divide (n,m);

cout<< "\n";

getch();

}

Remove or comment this block of function and discuss the expected result

Output

??

### Cont’d…

• Consider the following overloaded functions

#include<iostream.h>

#include<conio.h>

int max(int,int);

int max(int,int,int);

void main()

{

cout << max(99,77) << " " << max(55,66,33);

getch();

}

int max(intx,int y)

{ // returns the maximum of the two given integers:

return (x > y ? x : y);

}

int max(intx,int y, int z)

{ // returns the maximum of the three given integers:

int m = (x > y ? x : y); // m = max(x,y)

return (z > m ? z : m);

}

### Recursion

• All the functions we have seen up to now have been called by other functions

• A recursive function is a function that calls itself

• //recursion.cpp

#include<iostream.h>

#include<conio.h>

// returns the sum 1 + 2 + 3 + 4 +... + n

int sum(int x)

{

int s=0;

if(x==0)

return s;

else

return x + sum(x-1);

}

void main()

{

int n;

cout<<"\nEnter the last positive number to add the series: ";

cin>>n;

cout<<"The sum of the series is: "<<sum(n);

getch();

}

Sample Run

Enter the last positive number to add the series: 10

The sum of the series is: 55

### Recursive Functions

• //factorial.cpp

#include<iostream.h>

#include<conio.h>

long fact(long n)

{

// returns n! = n*(n-1)*(n-2)*...*(2)(1)

if(n == 0 || n ==1)

return 1;

else

return n*fact(n-1);

}

void main()

{

int num;

cout<<"\n Enter a number to find its factorial: ";

cin>>num;

cout <<"\n"<<num<<"! = "<<fact(num);

getch();

}

Sample Run

Enter a number to find its factorial: 6

6! = 720

### Exercise

• The following series is known as Fibonacci series, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ….

• Write a recursive function that generates and displays Fibonacci numbers

• Write a modular program that computes the following sum:

Sum = 1! + 2! + 3! + … + n!, where n is some positive integer

### Prototyping function

• Function prototypes are function declarations

• Consider the following declarations

int max(int,int);

int min(int,int,int);

void print();

float balance(float);

double totalSales(float price, int qty);

### Cont’d…

Function prototypes

#include <iostream.h>

#include <conio.h>

int max(int,int);

int min(int,int,int);

void main()

{

cout<<"\n maximum(99,77) = " <<max(99,77);

int x=55, y=66, z=33;

cout<<"\n minimum(x,y,z) = " << min(x,y,z);

getch();

}

int max(intx,int y)

{ // returns the maximum of the two given integers:

return (x > y ? x : y);

}

int min(intx,int y, int z)

{ // returns the maximum of the three given integers:

int m = (x < y ? x : y); // m = min(x,y)

return (z < m ? z : m);

}

### Cont’d…

In Function prototypes, parameter names are optional

#include <iostream.h>

#include <conio.h>

const float pi = 3.14159;

float area(float r);

float circumference(float r);

void main()

{

getch();

}

float area(float r)

{

return pi*r*r;

}

float circumference(float r)

{

return 2*pi*r;

}

### Next chapter: Structures

Test (15%): about 30 point questions