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

Ch4 - Functions

Uploaded by

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

Ch4 - Functions

Uploaded by

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

Principles of

Programming
Ch4 – Functions

Cpt. Rita Zaher – Principles of Programming – Ch4: Functions


Table of Content

• Introduction
• Math library functions
• Functions
• By value/ By reference/ By pointer Parameters
Introduction
• A function is a self-contained module that accomplishes a specific task defined outside the main
program (int main())
• It contains a set of instructions that will be executed when the function is called from the main
program.
• A function can be used over and over again  (Software reusability)

Ex: suppose a program that handles geometric shapes requires the calculation of the area of a circle 10 times with
different values. Instead of writing the same code 10 times, a function can be created that calculates the area.

• Programs use “new” and “prepackaged” modules


 New: programmer-defined functions.
 Prepackaged: from the standard library functions  those are functions predefined in the programming
environment. We call the library specified and then the function needed.
Introduction

When using functions:


• The program will be easier to understand, maintain and debug.
• Reusable codes that can be used in other programs
• A large program can be divided into smaller modules
 a large project can be divided among many programmers
Math library functions
• Perform common mathematical calculations:
Include the header file: #include <math.h> or #include <cmath>
• Functions called by writing:
- functionName (argument);
Or
- functionName(argument1, argument2, …);
• All functions in math library return a double

Ex: cout << sqrt( 900.0 );


// sqrt  (square root), the result is 30

• Function arguments can be:


- Constants  sqrt( 4 );
- Variables  sqrt( x );
- Expressions  sqrt( sqrt( x ) ) ;
 sqrt( 3 – 6*x );
Math library functions
Method Desc ription Example
ceil( x ) rounds x to the smallest integer ceil( 9.2 ) is 10.0
not less than x ceil( -9.8 ) is -9.0
cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0
(x in radians)
exp( x ) exponential function ex exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
fabs( x ) absolute value of x fabs( 5.1 ) is 5.1
fabs( 0.0 ) is 0.0
fabs( -8.76 ) is 8.76
floor( x ) rounds x to the largest integer floor( 9.2 ) is 9.0
not greater than x floor( -9.8 ) is -10.0
fmod( x, y ) remainder of x/y as a floating- fmod( 13.657, 2.333 ) is 1.992
point number
log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0
log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0
pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128
pow( 9, .5 ) is 3
sin( x ) trigonometric sine of x sin( 0.0 ) is 0
(x in radians)
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent of x tan( 0.0 ) is 0
(x in radians)
Math functions
Functions
Syntax:

return-value-type function-name( parameter-list with types)


{
declarations and statements //body of the function
}

• Return-value-type
- Data type of the result returned (int, float, char, bool…)
- Use “void “ if nothing is returned
• Parameter list
- Comma separated list of arguments + Data type for each argument.
- If no arguments, leave blank ()
Functions
void function_name() {
This is a procedure
cout<<“This is a procedure”;
}

A Function that
int main() { return nothing is
... called a
... Procedure
function_name();
...
...
return 0;
}
Functions
void function_name() {
...
...
} Returning type:
What is the data type that the function returns?
• void: it executes the code without returning anything
• int: it executes the code and returns an integer value
upon exiting the function
• float: it executes the code and returns a float value
upon exiting the function
• char: it executes the code and returns a character
value upon exiting the function
• Etc…
Functions
Write a function that prints “Hello World…” on the screen.

void printHello(){
cout<<"Hello World\n"; Hello World
cout<<"I am a procedure\n"; I am a procedure
cout<<"I can be called n times\n\n"; I can be called n times
}
Hello World
I am a procedure
int main(){ I can be called n times
printHello();
printHello(); Hello World
printHello(); I am a procedure
I can be called n times
}
Functions
void function_name(int a) {
...
Arguments:
... • To pass values from the program to a
} function
• A function can have multiple arguments
• Arguments should be of the same type as
int main() { the values to be passed from the program
... into the function
• If there is no arguments  () or we can write
...
void.
function_name(2);
...
...
function_name(2.5); // incorrect
return 0;
}
Functions Parameters:
Local variables from the main or
int function_name(int a) { from other functions are passed to
int b; function when called
... Local variables:
... • Known only in the function in which they are
return b; defined
• All variables declared in function definitions
} are local variables

int main() { return


int c; • Returns data, and control
c= function_name(2); goes to function’s caller
• If no data to return, in case
cout<< function_name(2); of a void function, use
return 0; “return;” or without the
keyword “return”
}
Functions
#include<iostream>

int a; //global variable

int main(){

int x; //local variable for main


...
While(int i){ // local for the loop
int y; //local for the bloc of code in the loop
...
}
cout<<y; // Incorrect local variable for the loop
cout<<a; // Correct, global variable
return 0;
}

//at this point, x and y do no exist.


//a is a global variable, exists in all the program
Functions
1) Function prototype  Declaration
- Tells the compiler about: argument type and return type of a function
 int square( int ); // takes an int and returns an int
 int power (int, int);
 void myfunction(char);

2) Calling/invoking a function  Using the function


Ex: int s = square(2);
• Pass argument 2
• Function gets its own copy of arguments
• After finished, passes back the result
• A function can be called from the main or from other functions.

3) Definition  function itself + body of the function


- Functions cannot be defined inside other functions.
Ex1
Write a program that calculates the square of 10 numbers taken from the user.

// Method 1: function written before the main

int square( int y ){ // function definition

return y * y;

} // end of the function

int main(){
int nb;
for ( int i=0; i<10; i++){
cout<<“Enter a number:”;
cin>>nb;
cout<< square(nb)<<endl; // calling the function
}
return 0;
Ex1

// Method 2: function written after the main  Need prototype


#include<iostream>
using namespace std;

int square(int); // prototype  declaration

int main(){
int nb;
for ( int i=0; i<10; i++){
cout<<“Enter a number:”;
cin>>nb;
cout<< square(nb); <<endl;
}
return 0;
}

int square( int y ){ // function definition


return y * y;
} // end of the function
Ex2
Write a function that calculates the sum of the numbers between 1 and n.
Write a program to call the function.

int Sum(int n){


int i, s=0; n S i s
for(i=1; i<=n; i++) 4 10 1 0
s+=i;
return s; 1
} 2 3
3 6
int main(){
int n, S; 4 10
cout<<“Input an integer: “; 5
cin>>n;
S = sum(n); Input an integer: 4
cout<<“The sum is: “<<S; The sum is 10
return 0;
}
Ex3
Write a program that calculates the factorial of an integer input by the user (use
void function).
x n i f
void factorial (int n){ 4 4 1 1
int i, f = 1;
2 2
for(i=1; i<=n; i++)
f = f * i; 3 6
cout<<f; 4 2
}
5
int main(){
int x;
cout<< “Input an integer: ”;
cin>>x;
cout<<“The factorial of ”<<x<<“ is ” factorial(x); // method 1
int res= factorial(x); //method 2
cout<<res; Input an integer: 4
return 0; The factorial of 4 is 24
}
Library for setw()
Ex4 / rand() function Library for rand()

rand();
 Scaling and shifting
Generates unsigned integer between 0 and
RAND_MAX (usually 32767)
x % y is between 0 and y – 1
Example
i = rand() % 6 + 1;
“Rand() % 6”: generates a number
between 0 and 5
“+ 1” makes the range 1 to 6

Number= shiftingValue + rand() % scalingFactor


shiftingValue = first number in desired range
scalingFactor = width of desired range

Ex: 3 <= x <= 20 0 <= rand()%18 <= 17


To generate a random number between a and b: 3 <= rand()%18+3 <= 20
a + rand () % ( b – a + 1 )
Call by value / by reference / By pointer
Parameters
Variables Address Memory
int main(){
int x; Xx 0 5

x=5; Y 1 2

int y, z; Z 2 7
y=2; 3
z=x+y; // z= 5+2 = 7 4

5
return (0);
6
}
Call by value / by reference / By pointer
Parameters
int main(){ Variables Address Memory
… X 0 3
5 x and y variables not modified
x=3; Y 1 2
z= add(x, y); Call by value
Z 2 5
7
- Copy of data passed to
return (0); the function parameters.
3
} - Changes to copy do not
4 change original data
a 5 3
int Add (int a, int b){
return a+b; b 6 2

}
Call by value / by reference / By pointer
Parameters
Variables Address Memory
int main(){
… X 0 23
cout<< x << endl; Call by reference
Y 1 2
changeVar(x) ; - A link is created between
Z 2 5 the original data and the
cout<< x << endl; parameters in the
return (0); 3 function.
} c 4 23 - Any changes in the
parameters leads to a
a 5 3 change in the original
void changeVar (int &c){ data.
b 6 2
c=2;
} 3
2
Call by value / by reference / By pointer
Parameters
int main(){ Variables Address Memory
… X 0 3
2
cout<< x << endl; Call by pointer
Y 1 2
changeVar(&x) ; - Function can directly
// (&x)=(0) Z 2 5
access data.
cout<< x << endl; 3 - Changes affect original
return (0); data.
c 4 0
}
a 5 3
void changeVar (int* c){
*c = 2 ; b 6 2
 *(&x)=*(0)=2 3
} 2
Ex5

void swap1 (int x , int y) { // by value parameters


Before: nb1 = 2, nb2 = 4
int aux; After: nb1 = 2, nb2 = 4
aux = x;
x = y;
y = aux; Variables Address Memory
}
X 0 42

int main(){ Y 1 24

int nb1 = 2, nb2 = 4; aux 2 2


cout << “Before: " << "nb1 = " << nb1 <<", nb2 = " << nb2 << endl; 3
swap1(nb1,nb2); nb1 5 2
cout << “After:" << "nb1 = " << nb1 <<", nb2 = " << nb2 << endl; nb2 6 4
return (0);
}
Ex5

Before: nb1 = 2, nb2 = 4


void swap2(int &x , int &y) { // by reference parameters After: nb1 = 4, nb2 = 2
int aux;
aux = x;
x = y;
y = aux; Variables
Variables Address
Address Memory
Memory
} XX 00 24
YY 11 42
int main(){
aux
aux 22 2
int nb1 = 2, nb2 = 4;
33
cout << “Before:" << "nb1 = " << nb1 <<", nb2 = " << nb2 << endl;
nb1 55 2
swap2(nb1,nb2);
cout << “After :" << "nb1 = " << nb1 <<", nb2 = " << nb2 << endl; nb2 66 4
return (0);
}
Ex5

Before: nb1 = 2, nb2 = 4


void swap2(int *x , int *y) { // by pointer parameters After: nb1 = 4, nb2 = 2
int aux;
aux = *x;
*x = *y;
*y = aux; Variables Address Memory
} X 0 5
Y 1 6
int main(){
aux 2 2
int nb1 = 2, nb2 = 4;
3
cout << “Before:" << "nb1 = " << nb1 <<", nb2 = " << nb2 << endl;
swap2(&nb1,&nb2); nb1 5 42
cout << “After :" << "nb1 = " << nb1 <<", nb2 = " << nb2 << endl; nb2 6 24
return (0);
}
Ex6
Write a function that take a grade from the user. Call the function from the main.

//Method 1: //Method 2:
float Enter_Grade (){ void Enter_Grade (float &n){
float n; do{
do{ cout<<“Enter grade”;
cout<<“Enter grade”; cin>> n;
cout<< n; }while(n<0 || n>100);
}while(n<0 || n>100); }
return n;
} int main(){
float grade;
int main(){ Enter_Grade (grade);
float grade; return 0;
grade = Enter_Grade(); }
return (0);
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy