COMP 003 Module 2 Functions
COMP 003 Module 2 Functions
Functions
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
#include <iostream>
#include <stdlib.h> Input Arguments
int main(){
for (double i=40 ; i <= 100 ; i+=5)
cout <<"weight("<< i <<") = " << weight(i) << endl;
system("PAUSE"); return 0;
}// end of main
Assignment # 2
1. White a program to calculate the
GPA in First semester.
The program asks the marks out
of 100 in each subject and
calculates GPA.
It also calculates the
percentage marks in the first
semester.
Here is an example for
calculation
#include <iostream>
#include <stdlib.h>
using namespace std;
void f(int x, int &y){ // changes reference argument to 99:
x = 88;
y = 99;
}
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()
{
int x = 50; // local variable x
cout << "I m local x and x = " << x << endl;
cout << "I m global x and x = " << ::x << endl;
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 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
n!
1. Implement the permutation n
Cr
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.