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

Chapter 5 Functions 1 notes and examples

Chapter 5 function of a computer programming lecture notes snd examples for freshman university students

Uploaded by

bamnetesfaye
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)
8 views

Chapter 5 Functions 1 notes and examples

Chapter 5 function of a computer programming lecture notes snd examples for freshman university students

Uploaded by

bamnetesfaye
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/ 33

Chapter 5

Functions

1
Functions
• A function is a collection of statements that perform a
specific task.
• A c++ program is typically written by combining new
functions with “prepackaged” functions available in C+
+ Standard Libraries.
• Most useful programs are much larger than the
programs that we have considered so far. To make
large programs manageable, we modularize them into
subprograms.
• Functions allow the programmer to modularize a
program by separating its tasks into self-contained
units.
• Once a function is written, it can be called within
other parts of the program. 2
C++ Library Functions

3
Standard C++ Library Functions
• is a collection of pre-defined functions and
other program elements which are accessed
through header files.
• Its actual code is hidden away within the Standard
C++ Library.
• Example :
• the sqrt() function defined in <cmath>

User Defined Functions


The functions provided by the Standard C++ Library are
still not sufficient for most programming tasks.
Programmers also need to be able to define their own
functions. 4
Syntax to create a function
type FunctionName( type Parameter1, type Parameter 2,…)
{
//Body of function goes here
}
Example: 1) int areaOfRectangle(int base, int height)
{
int area=base*height;
return area;
}
2) float cube(float x)
{
float cube=x*x*x;
return cube;
} 5
Example
#include<iostream>
int AddTwoNumbers(); Function prototyping
using namespace std;
int main()
{
float x; Function calling
x=AddTwoNumbers();
cout<<“a+b=”<<x;
return 0;
Function definition
}
float AddTwoNumbers()
{
float a=2.87;
float b=7.75;
float c=a+b;
return c;
} 6
Function Prototypes

• Before the compiler encounters a call to a particular


function, it must already know certain things about the
function.
• In particular, it must know the number of parameters the
function uses, the type of each parameter, and the
return type of the function.
• One way of ensuring that the compiler has this required
information is to place the function definition before all
calls to that function.
• Another method is to declare the function with a
function prototype.
7
Contd…
• E.g.
• float AddTwoNumbers();
• This prototype looks similar to the function
header, except there is a semicolon at the
end.
• Function prototypes are usually placed near
the top of a program so the compiler will
encounter them before any function calls.

8
Calling a Function
• A function is executed when it is called.
• Function main is called automatically when a
program starts, but all other functions must
be executed by function call statements.
• A function call is simply the name of the
function followed by a set of arguments
enclosed in parentheses and a semicolon.
• E.g.
x=AddTwoNumbers();

9
Function definition
• A function definition contains the statements
that make up the function.
• All function definitions have the following
parts:
• Return type ,Name, Parameter list and Body :

10
Contd… h as
#include <iostream> tio n
n i
int add( int a, int b); //function declaration or prototyping defi
ction
int main() , f un
e l le d
{ can c on
n is uncti
int a,b; ratio ain f
d e cla re m
cout<< "Enter Two integers " <<endl; : If e befo
.B
N om
cin>> a >> b; oc t
cout<< "The sum of "<< a << " and " << b << " is " << add( a , b ); // function call
return 0;
}
int add(int a , int b) // function definition
{
int sum;
sum=( a + b ); // Replace function call with sum
return sum;
}
11
#include<iostream> prototype
using namespace std;
float AddTwoNumbers(float a, float b);
int main()
{
float n, m;
cout<<“Enter first number:”;
cin>>n;
cout<<“Enter second number:”;
cin>>m;
cout<<n<<“+”<<m<<“=”<<AddTwoNumbers( n, m );
return 0;
}
float AddTwoNumbers(float a, float b)
{
return a+b; definition
} 12
Scope of variables
• Scope: is the portion of a program where an
identifier or a variable name can be used
»Function scope
»File scope
»Block scope
»Function-prototype scope (program
scope)

13
14
Example
#include<iostream>
using namespace std;
int main()
{
int x=0;
for(int b=0;b<5;b++)
{
int k=15;
x+=b; ‘b’ & ‘k’ are accessible only
cout<<b; in this block
}
cout<<x;
cout<<b; ‘b’ & ‘k’ are not declared
cout <<k; in this scope
return 0;
15
}
Argument passing By Argument passing By
Value Reference
We call function addition We call function addition
passing the values of x passing the references
and y ( 5 and 3 of x and y (that means
respectively), not the references of 5 and 3
variables themselves. respectively) ,not the
values.

16
Example on Argument Passing by reference
//parameters passing by reference
#include<iostream>
int duplicate( int &a,int &b,int &c)
{
a*=2;
b*=2;
c*=2;
}
int main()
{
int x=1,y=3,z=7;
duplicate(x,y,z);
cout<<"x="<<x<<" "<<"y="<<y<<" "<<"z="<<z;
return 0;
}
17
Example on Argument Passing by value
#include<iostream>
using namespace std;
int add(int number);
int main()
{
int number,result;
number=5;//enter a number
cout << " The initial value of number is " << number << endl;
result=add(number);
cout << " The final value of number is " << number << endl;
cout << " The result is : " << result << endl;
return(0);
}
int add(int number)
{
number=number+100;
return(number);
} 18
#include<iostream>//example two by reference
using namespace std;
int add(int &number);
int main ()
{
int number;
int result;
number=5;
cout << "The value of the variable number before calling the function : " << number <<
endl;
result=add(number);
cout << "The value of the variable number after the function is returned : " << number <<
endl;
cout << "The value of result : " << result << endl;
return(0);
}
int add(int &p)
{
p=p+100;
return p;
} 19
Returning More than one value
//More than one returning value
#include<iostream.h>
void prevnext(int x,int &prev,int &next)
{
prev=x-1;
next=x+1;
}
int main()
{
int x=100,y,z;
prevnext(x,y,z);
cout<<“Previous=”<<y<<“,Next=”<<z;
return 0;
}
//out previous=99,next=101
20
Function Overloading
Means defining functions having the same name
but that take different parameters
#include<iostream.h>
int divide(int a,int b)
Function overloading
{
return (a/b);
Are functions with the same
} name having:
float divide(float a,float b)
{
Different number of
return(a/b); argument
}
 Different type of argument
int main() Both
{
int x=5,y=2; float n=5.0,m=2.0;
cout<<divide(x,y);
cout<<"\n";
cout<<divide(n,m);
21
return 0;}
//illustrates overloading the function name ave.
#include <iostream>
using namespace std;
double ave(double n1, double n2);
double ave(double n1, double n2, double n3);
int main( ) {
cout << "The average of 2.0, 2.5, and 3.0 is "<< ave(2.0, 2.5, 3.0) << endl;
cout << "The average of 4.5 and 5.5 is "<< ave(4.5, 5.5) << endl;
return 0;
}
double ave(double n1, double n2) Two argument
{
return ((n1 + n2)/2.0);
}
double ave(double n1, double n2, double n3) Three Argument
{
return ((n1 + n2 + n3)/3.0);
} 22
int addition (int a, int b)
int addition (int a, int b)
{
{
int r;
int r;
r=a+b;
r=a+b;
return (r);
return (r);
}
}
float addition (float a, float b)
int addition (int a, int b, int c)
{
{
float r;
int r;
r=a+b;
r=a+b+c;
return (r);
}
return (r);
int main ()
}
{
int main ()
int z; float y; {
z = addition (5,3); int z; float y;
y = addition (5.5,3); z = addition (5,3);
cout << "The result is " << y = addition (5,5,3);
z<<endl<<y; cout << "The result is " << z<<endl<<y;
return 0; return 0;
} }
23
Excercise
1. Suppose you have two function definitions with the following
declarations:
double score(double time, double distance);
int score(double points);
Which function definition would be used in the following function call and
why would it be the one used? (x is of type double.)
double finalScore = score(x);

2. Suppose you have two function definitions with the following


declarations:
double theAnswer(double data1, double data2);
double theAnswer(double time, int count);
Which function definition would be used in the following function call and
why would it be the one used? (x and y are of type double.)
x = theAnswer(y, 6.0);
24
Default values in arguments
#include<iostream.h> N.B
int divide(int a, int b=2)
{ • Though the 2nd parameter
int r; is not specified when
r=a/b;
return(r);
calling function “divide”
} it takes the 2nd value of
int main() divide function that is
{
cout<<divide(12);//6 found @ function
cout<<endl; prototyping i.e. the default
cout<<divide(20,4);//5
return 0;
value in argument.
}
//out put 6 and 5
25
include <iostream>
Using namespace std;
void showVolume(int length, int width = 1, int height = 1);
int main( )
{
showVolume(4, 6, 2);
showVolume(4, 6);
showVolume(4);
return 0;
}
void showVolume(int length, int width, int height)
{
cout << "Volume of a box with \n“
<< "Length = " << length << ", Width = " << width << endl<<
"and Height = " << height<<
" is " << length*width*height << endl;
} 26
Recursive functions:
• Is Function that calls themselves.
Example 6
long factorial(long n)
{
if(n==0)return 1;
else
return n*factorial(n-1);
}
Or
int Factorial (unsigned int n)
{
return n == 0 ? 1: n * Factorial (n-1);
}
27
Void main()
{
int n;
cout<<”enter a +ve number:”;
cin>>n;
cout<<”the factorial of
”<<n<<”is”<<factorial(n);
}

28
Recursively
• //factorial calculator
#include<iostream.h>
long factorial (long a)
{
if(a>1)
return (a* factorial(a-1));
else
return 1;
}
int main()
{
long l;
cout<<"Type a number:";
cin>>l;
cout<<"!"<<l<<"="<<factorial(l);
return 0;
} 29
Inline Function
• If a function is inline, the compiler places a copy of
the code of that function at each point where the
function is called at compile time.
• To inline a function, place the keyword inline before
the function name and define the function before any
calls are made to the function.

30
Passing array as argument to a function
 We pass both array and its size to a
function.
 Array are passed as reference variable
without (&)
Example.
double read(int a[],int size);
 When we call function with array parameter
we simply pass array name and size.
read(a,size);
31
// the use of function prototype
#include<iostream.h>
int area(int length,int width);
int main()
{
int l;
int w;
int areaofrect;
cout<<"enter lenth of the rectangle:";
cin>>l;
cout<<"Enter width of the rectangle:";
cin>>w;
areaofrect=area(2,10);
cout<<"Area of the rectangle:"<<areaofrect<<endl;
return 0;
}
int area( int l,int w)
{
return l*w;
} 32
#include<iostream.h>
int Volume(int length,int width=5,int height=1);
int main()
{
int length=2,width=2,height=3;
int volume;
volume = Volume(length, width, height);
cout<<"First area equals:"<<volume<<"\n";//12
volume = Volume(length, width);
cout<<"second area equals:"<<volume<<"\n";//4
volume= Volume(length);//
cout<<"Third area equals:"<<volume<<"\n";
return 0;
}
Int Volume(int length, int width, int height)
{
return(length * width * height);
}

33

You might also like