0% found this document useful (0 votes)
0 views

COMP 003 Module 2 Functions

The document provides an overview of functions in programming, explaining their purpose, usage, and various types such as passing by value, passing by reference, and recursion. It includes examples of function definitions, declarations, and practical applications like calculating factorials, permutations, and GPA. Additionally, it outlines assignments for implementing specific functions and concepts related to functions.

Uploaded by

ysabel2k22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

COMP 003 Module 2 Functions

The document provides an overview of functions in programming, explaining their purpose, usage, and various types such as passing by value, passing by reference, and recursion. It includes examples of function definitions, declarations, and practical applications like calculating factorials, permutations, and GPA. Additionally, it outlines assignments for implementing specific functions and concepts related to functions.

Uploaded by

ysabel2k22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Programming 2

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

using namespace std;


int cube(int x); // function declaration

int main(){ // tests the cube() function:


int n = 1;
while (n != 0){
cout <<"Enter a Number: "; cin >> n;
cout << "\tcube(" << n << ") = "
<< cube(n) << endl; // Calling a function
} // end of while loop
system("PAUSE"); return 0;
}//end of main Return type
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>
#include <stdlib.h>
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;
// returns n! = n*(n-1)*(n-2)*...*(2)
long double fact(long double n){
if (n < 0) // if n is negative
exit(-1); // close the program
long double f = 1;
while (n > 1)
f *= n--; //1st f=f*n then n decrements
return f;
}
int main(){ // tests the factorial() function:
for (long double i=0 ; i < 1760 ; 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 r){ // returns n Permutation k


if ( n<0 || r<0 || r>n )
exit (-1);
return fact(n)/fact(n-r);
}
Calculating Permutations
int main(){ // tests the perm() function:
int n,r;
cout << "Enter n: "; cin >> n;
cout << "Enter r: "; cin >> r;
cout << n << " P " << r << " = " << perm(n,r) << " ";
cout << endl;
system("PAUSE");
return 0;
}//end of main
GPA Calculator
// Calculates Weight
#include <iostream>
#include <stdlib.h>
using namespace std;
double weight(double marks) {
if (marks >= 80) return 4.0; // A
else if (marks >= 75) return 3.5; // B+
else if (marks >= 70) return 3.0; // B
else if (marks >= 65) return 2.5; // C+
else if (marks >= 60) return 2.0; // C
else if (marks >= 55) return 1.5; // D+
else if (marks >= 50) return 1.0; // D
else if (marks >= 0) return 0.0; // F
}

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

Cred Grad Wei Grade


Code Course Title Marks
it Hr. e ght Points
GR103 Arabic-I 2 80 A 4 8
EN101 Communication Skills 3 75 B+ 3.5 10.5
BS110 Applied Calculus 3 70 B 3 9
BS100 Engineering Physics 3 65 C+ 2.5 7.5
EE100 Circuit Analysis-I 3 60 C 2 6
CS100 Fundamentals of Programming 1 55 D+ 1.5 1.5
EE102 Workshop Practice 1 80 A 4 4
EE100L Circuit Analysis-I Lab 1 75 B+ 3.5 3.5
CS100L Fundamentals of Programming Lab 1 70 B 3 3

Total Grade Points in 1st Semster 53


Total Credit Hours 18
Semester GPA (SGPA)
Semester Commulative Percentage
2.94
69.44
Download this app
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

// this function returns the area and circumference of a circle


void computeCircle(double& area, double& circumference,
const double& 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 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 #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.

4. 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 inside the function.
Assignment #3
5. 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 0, because base 0 = 1.

6. Write a program to solve


tower of Hanoi problem
through recursive functions

You might also like