You are on page 1of 24

Introduction to Programming

Engr. Rashid Farid Chishti


chishti@iiu.edu.pk
Chapter 05: Functions

International Islamic University H-10, Islamabad, Pakistan


http://www.iiu.edu.pk

Functions

A function groups a number of program


statements into a unit and gives it a name.
This unit can then be invoked from other parts
of the program.
The most important reason to use functions is
to aid in the conceptual organization of a
program
Another reason to use functions is to reduce
program size. Any sequence of instructions
that appears in a program more than once is a
candidate for being made into a function.
The functions code is stored in only one
place in memory, even though the function is
executed many times in the course of the
program.

Return type

Input arguments

Functions
//demonstrates a simple function
#include <iostream>
using namespace std;
int cube(int x);
// function deration
int main(){
// tests the cube() function:
int n = 1;
Input Arguments
while (n != 0){
cin >> n;
cout
<< "\tcube(" << n << ") =
<< cube(n) << endl; // Calling a function
}
// end of while loop
system("PAUSE"); return 0;
Return type
}//end of main
int cube( int x ){ // function definition
return x*x*x;
// returns cube of x:
}
// { function body }

Functions

Each integer read is passed to the cube() function by the


call cube(n). The value returned by the function replaces
the expression cube(n) and then is passed to the output
object cout

The main() function passes the value 5 to the cube()


function, and the cube() function returns the value 125
to the main() function.

The argument n is passed by value to the formal parameter


x. This simply means that x is assigned the value of n
when the function is called.

Two Argument Functions


//Calculates max of two Numbers
#include <iostream>
using namespace std;
int max(int , int );
// function deration
int main(){
// tests the max() function:
int m = 1, n;
while ( m != 0){
cin >> m >> n;
cout
<< "\tmax(" << m <<","<<n<< ") = "
<< max(m,n) << endl; // Calling a function
}
// end of while loop
system("PAUSE"); return 0;
}
//end of main
int max( int x, int y){
// function definition
return (x > y ? x:y);
// returns max of two:
}
// { function body }

Writing function before main


// Calculates Factorial
#include <iostream>
#include <stdlib.h>
using namespace std;
long fact(int n){ // returns n! = n*(n-1)*(n-2)*...*(2)(1)
if (n < 0) return 0;
int f = 1;
while (n > 1)
f *= n--;
// first f=f*n then n decrements
return f;
}
int main(){ // tests the factorial() function:
for (int i=-1; i < 6; i++)
cout << i <<"!= " << fact(i) << endl;
system("PAUSE"); return 0;
}//end of main

Calculating Permutations
// Calculates Permutation using Factorial
#include <iostream>
#include <stdlib.h>
using namespace std;
long fact(int n){ // returns n! = n*(n-1)*(n-2)*...*(2)(1)
if (n < 0) return 0;
int f = 1;
while (n > 1)
f *= n--;
// first f=f*n then n decrements
return f;
}
long perm(int n, int k){ // returns n Permutation k
if ( n<0 || k<0 || k>n ) return 0;
return fact(n)/fact(n-k);}

Calculating Permutations
int main(){ // tests the perm() function:
for (int i=-1 ; i < 6; i++){
for (int j=-1; j <=i+1 ; j++)
cout << i << "P" << j << "=" << perm(i,j) << " ";
cout << endl;
}
system("PAUSE"); return 0;
}//end of main

Passing by Value and Passing by Reference


#include <iostream>
#include <stdlib.h>
using namespace std;
void f(int x, int &y){ // changes reference argument to 99:
x = 88;
y = 99;
}
int main(){ // tests the f() function:
int a = 22,b = 44;
cout << "a = " << a << ", b = " << b << endl; // 22,44
f(a,b);
cout << "a = " << a << ", b = " << b << endl; // 22,99
f(2*a-3,b);
cout << "a = " << a << ", b = " << b << endl; // 22,99
system("PAUSE"); return 0;
}//end of main

Passing by Value and Passing by Reference


#include <iostream>
#include <stdlib.h>
using namespace std;
void swap(float &x, float &y){ // exchanges value of x and y
float temp = x;
x = y;
y = temp;
}
int main(){ // tests the swap() function:
float a = 22.2, b = 44.5;
cout << "a = " << a << ", b = " << b << endl;
swap(a,b);
cout << "a = " << a << ", b = " << b << endl;
cout << &a = " << &a << ", &b = " << &b << endl;
system("PAUSE"); return 0;
}//end of main

Returning More than One Value


#include <iostream>
#include <stdlib.h>
using namespace std;
void computeCircle( double&, double&, const double& );
int main(){ // tests the computeCircle() function:
double r,a,c; cout << "Enter radius: "; cin >> r;
computeCircle(a, c, r);
cout << "Area = " <<a<<", Circumference = " <<c<< endl;
system("PAUSE"); return 0;
} // end of main
void computeCircle(double& area, double& circumference,
const double& r){ // returns the area and circumference
// of a circle with radius r:
const double PI = 3.141592653589793;
area = PI*r*r;
circumference = 2*PI*r;
}

Local and Global Variables


#include <iostream>
#include <stdlib.h>
using namespace std;
int x = 10; // a global variable x
int main(){
int x = 50; // local variable x
cout << "I m local x and x = " << x << endl;
cout << "I m global x and x = " << ::x << endl;
x = 70;
// modify local x
:: x = 30; // modify global x
cout << "New value of local x = " << x << endl;
cout << "New value of global x = " << ::x << endl;
system("PAUSE"); return 0;
}

Default Arguments
#include <iostream>
#include <stdlib.h>
using namespace std;
//declaration with default arguments
void repchar(char='*', int=45);
int main(){
repchar();
//prints 45 asterisks
repchar('=');
//prints 45 equal signs
repchar('+', 30); //prints 30 plus signs
system("PAUSE"); return 0;
}
void repchar(char ch, int n){// displays line of characters
// defaults supplied if necessary
for(int j=0; j<n; j++)
// loops n times
cout << ch;
// prints ch
cout << endl;
}

Inline Function

A function call involves substantial overhead.


Extra time and space have to be used to invoke
the function, pass parameters to it, allocate
storage for its local variables, store the
current variables and the location of execution
in the main program, etc.
In some cases, it is better to avoid all this
by specifying the function to be inline. This
tells the compiler to replace each call to the
function with explicit code for the function.
To the programmer, an inline function appears
the same as an ordinary function, except for
the use of the inline specifier.

Inline Function
// demonstrates inline functions
#include <iostream>
#include <stdlib.h>
using namespace std;
inline float lbstokg(float pounds){
// converts pounds to kilograms
return 0.453592 * pounds;
}
int main(){
float lbs;
cout << "\nEnter your weight in pounds: "; cin >> lbs;
cout << "Your weight in kilograms is " << lbstokg(lbs)
<< endl;
system("PAUSE");
return 0;
}

Function Overloading
// Calculates Factorial
#include <iostream>
#include <stdlib.h>
using namespace std;
int add(int a, int b){
cout << " Calling Int " << endl; return a+b;
}
float add(float a, float b){
cout << " Calling float " << endl; return a+b;
}
int main(){ // tests the factorial() function:
cout << add(5,3) << endl; // Calls int add( int, int)
cout << add(5.5F, 4.7F) << endl; // Calls float version
system("PAUSE"); return 0;
}//end of main

Recursion

The existence of functions makes possible a


programming technique called recursion.
Recursion involves a function calling
itself. This sounds rather improbable, and
indeed a function calling itself is often a
bug. However, when used correctly this
technique can be surprisingly powerful.
Recursion is much easier to understand with
an example than with lengthy explanations,
so lets apply it to a program weve seen
before:
The next program, uses recursion instead of
a loop to calculate factorial.

Recursion
#include <iostream>
#include <stdlib.h>
using namespace std;
// calls itself to calculate factorials
unsigned long fct(unsigned long n){
static int I = 0; I++;
cout << "You Called Me " << I << " times" << endl;
if(n > 1)
return n * fct(n-1);
//self call
else
return 1;
}
int main(){
int n; cout << "Enter an integer: "; cin >> n;
cout << "Factorial of " << n << " is " << fct(n) << "\n";
system("PAUSE"); return 0;
}

Recursion

Returning by Reference

Besides passing values by reference, you can also


return a value by reference.
The reason is to allow you to use a function call on
the left side of the equal sign.
variable returned by the function is assigned the
value on the right side of the equal sign.
You cant return a constant from a function that
returns by reference.

int& seta(){
return 3; // Error
}

You cant return a reference to a local variable:

int& seta(){
int x = 3;
return x; // error
}

Returning by Reference
#include <iostream>
#include <stdlib.h>
using namespace std;
int a = 10;
int& seta(){ // return type is int&
return a; //only global var can be returned by reference
}
int main(){
cout << "a = " << a << endl;
int b = 20;
b = seta() + b; // seta is used as a value
cout << "b = " << b <<endl;
seta() = b + 20; // seta is used as a variable
cout << "a = " << seta() <<endl;
system("PAUSE"); return 0;
}

Assignment #3
1.

2.

3.

4.

n!
Cr
r!(n r )!

Implement the permutation


through perm() function
Write a function that returns GCD (Greatest
Common Divisor) of two Numbers.
Write a function that returns LCM (Least
Common Multiple) of two Numbers.
Write a recursive function power( base,
exponent ), when invoked, returns base exponent.
For example, power( 3, 4 ) = 3 * 3 * 3 * 3.
Assume that exponent is an integer greater
than or equal to 1. Hint: The recursion step
would use the relationship
base exponent = base base (exponent 1)
and the terminating condition occurs when
exponent is equal to 1, because base 1 = base.

Assignment #3
1.

Write a function to determine the prime


factors of a number by defining the function
Pfactors
e.g., prime factors of 24 are 2,2,2,3 and
35 are 5,7
Display the result in the function.

You might also like