Professional Documents
Culture Documents
Introduction To Programming: Engr. Rashid Farid Chishti
Introduction To Programming: Engr. Rashid Farid Chishti
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 function’s 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
#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;
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 let’s apply it to a program we’ve 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 can’t return a constant from a function that
returns by reference.
int& seta(){
return 3; // Error
}
You can’t 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 #5
1. Implement the permutation nC
n!
r
through perm() function r!(n r )!
2. Write a function that returns GCD (Greatest
Common Divisor) of two Numbers.
3. Write a function that returns LCM (Least
Common Multiple) of two Numbers.