CPP CH#5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

SALALE UNIVERSITY

COLLEGE OF ENGINEERING AND TECHNOLOGY


(Pre – Engineering)

Computer Programming
(ECEg 1013)

Course Instructor:
Haylemaryam G. (M.Sc. in ECEg)

Fiche, Ethiopia
May 27, 2024
CHAPTER V
Functions
➢ Function Declaration and Definition
➢ Passing Value by Value and Passing Value by Reference
➢ Function Overloading
➢ Default Argument
➢ Inline Function and Recursive Functions

By: Haylemaryam G. (MSc in ECEg.) 2


Function Basics
➢ A function is a collection of statements that performs 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. These subprograms are called functions.
➢ They can be compiled and tested separately and reused in different
programs.
➢ In short: function is block of instruction that is executed when it is
called form some other point of a program.
By: Haylemaryam G. (MSc in ECEg.) 3
Functions: Analogy
Boss To Worker Analogy:
➢ A Boss (the calling/caller function) asks a worker (the called function) to
perform a task and return result when it is done.

By: Haylemaryam G. (MSc in ECEg.) 4


The Uses of functions:
▪ Avoid redundancy
▪ Size reduction of code
▪ Code reusability
▪ Increase readability
Standard C++ Library Functions
➢ The Standard C++ Library 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. e.g.:
INT_MAX constant defined in <climits>
the sqrt() function defined in <cmath>
the rand() function defined in <cstdlib>
the time() function defined in <ctime>

By: Haylemaryam G. (MSc in ECEg.) 5


The Square Root Function sqrt()
➢ We can visualize the function as follow:
Y = sqrt(x);

By: Haylemaryam G. (MSc in ECEg.) 6


Example:
#include<cmath> // defines the sqrt() function
#include<iostream> // defines the cout object
using namespace std;
int main()
{ // tests the sqrt() function:
for (int x=0; x<6; x++)
cout<<"\t"<<x<<"\t"<<sqrt(x)<<endl;
}
Output:

By: Haylemaryam G. (MSc in ECEg.) 7


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.
➢ Example: A cube() Function
...
int cube(int x)
{ // returns cube of x:
return x*x*x;
}
...
➢ The function returns the cube of the integer passed to it. Thus the call
cube(2) would return 8.
By: Haylemaryam G. (MSc in ECEg.) 8
➢ A user-defined function has two parts: its head and its body.
Syntax:
return_type function_name (parameter_list) // head of function
{
// statement /body of function
}
where:
▪ function_name : a unique name for the function. Naming rules are the same as
those for variables.
▪ parameter_list : a list of variables that hold values being passed to the function.
▪ body : the set of statements that make up the function/ actual task. Including the
return statement that specifies the return value to the calling program.
▪ return_type: the data type of the value being sent back from the function.
By: Haylemaryam G. (MSc in ECEg.) 9
➢ The syntax for the head of a function is:
return_type function_name (parameter_list)
➢ This specifies for the compiler the function’s return type, its name, and its
parameter list.
➢ In above example, the function’s return type is int, its name is cube,
and its parameter list is int x.
➢ So its head is:
int cube(int x)
➢ The body of a function is the block of code that follows its head.
➢ It contains the code that performs the function’s action/ actual task,
including the return statement that specifies the return value to the calling
program.
By: Haylemaryam G. (MSc in ECEg.) 10
➢ The body of the cube function is:
{ // returns cube of x:
return x*x*x;
}
➢ Note that main() itself is a function. Its head is: int main() or void main()
and its body is the program itself.
➢ Its return type is int or none , its name is main, and its parameter list is
empty.
➢ A function’s return statement serves two purposes: it terminates the
execution of the function, and it returns a value to the calling program.
➢ Its syntax is:
return expression;
By: Haylemaryam G. (MSc in ECEg.) 11
➢ Where expression is any expression whose value could be assigned to a
variable whose type is the same as the function’s return type.
Example: test drivers: simple program to test our functions.
int cube(int x)
{ // returns cube of x: Output:
return x*x*x;
}
int main()
{ // tests the cube() function:
int n=1;
while (n!=0)
{
cin>>n; cout<<"\tcube("<<n<<")="<<cube(n)<<endl;
}
}
By: Haylemaryam G. (MSc in ECEg.) 12
Function Declaration/ 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.
Example: 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.
By: Haylemaryam G. (MSc in ECEg.) 13
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.

Example:
x = AddTwoNumbers();

By: Haylemaryam G. (MSc in ECEg.) 14


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

By: Haylemaryam G. (MSc in ECEg.) 15


Example:
#include<iostream>
using namespace std;
float AddTwoNumbers(); Function declaration/ prototyping
int main()
{
float x;
x = AddTwoNumbers(); Function calling
cout<<x;
return 0;
}
float AddTwoNumbers() Function definition
{
float a=2.87, b=7.75;
float c=a+b; Output:
return c;
}
By: Haylemaryam G. (MSc in ECEg.) 16
Example:
int addition (int a, int b)
{
int r;
r = a+b;
return (r);
}
int main ()
{
int z;
z = addition(5,3);
cout<<"The result is "<<z;
return 0;
}
By: Haylemaryam G. (MSc in ECEg.) 17
Function example
#include<iostream>
using namespace std;
int subtraction (int a, int b)
{
int r; r=a-b; return(r);
}
int main ()
{
int x=5, y=3, z;
z = subtraction (7,2);
cout<<"The first result is "<<z<<'\n’;
z = 4 + subtraction(x,y);
cout<<"The second result is "<<z<<'\n';
return 0;
}
By: Haylemaryam G. (MSc in ECEg.) 18
Prototyping Function:
Syntax:
data_type name(param1, param2, param3,…, paramn);

i.e. function head followed semicolon.

➢ NB. We can define a function bellow the main function but the
declaration must be before the main function, i.e. declaration is
prototype.

By: Haylemaryam G. (MSc in ECEg.) 19


Example: //function declaration
int addition (int a, int b);
int main ()
{
int z;
z = addition(5,3);
cout<<"The result is "<<z;
return 0;
}
int addition (int a, int b)
{
int r;
r = a+b;
return (r);
}
By: Haylemaryam G. (MSc in ECEg.) 20
Functions with no return types
➢ These functions don’t return value. they may have no parameter at all.
i.e. .We will make their return type void.
Example:
void printmessage ()
{
cout<<"I'm a function!";
}
int main ()
{
printmessage ();
return 0;
}

By: Haylemaryam G. (MSc in ECEg.) 21


Argument Passing
➢ Also known as function calling. There are two types of function calling.
1. Pass-by-Value
2. Pass-by-Reference

Pass-by-Value
➢ Means passing copies of value of variables but never the variables
themselves.
➢ The variable is unaffected by the function. Thus the variable is a read only
parameter.

By: Haylemaryam G. (MSc in ECEg.) 22


Example: pass-by-value Output:
void new(int, int);
int main()
{ // tests the new() function:
int a=22, b=44;
cout<<"a ="<<a<<",b ="<<b<<endl;
new(a,b);
cout<<"a ="<<a<<",b ="<<b<<endl;
new(2*a-3,b);
cout<<"a ="<<a<<",b ="<<b<<endl;
}
void new(int x, int y)
{
x = 88;
y = 99;
}
By: Haylemaryam G. (MSc in ECEg.) 23
Pass-by-Reference
➢ Means passing variables themselves.
➢ Use the ampersand (&).
➢ The variable is affected by the function. Thus the variable is a read-write
parameter.
i.e. Any change to the local variable inside the function will cause the
same change to the argument that was passed to it.

By: Haylemaryam G. (MSc in ECEg.) 24


Example: pass-by-reference
void swap(float&, float&); // exchanges the values of x and y;
int main()
{ // tests the swap() function:
float a=22.2, b=44.4;
cout<<"a = "<<a<<",b = "<<b<<endl;
swap(a,b);
cout<<"a = "<<a<<",b = "<<b<<endl;
}
void swap(float& x, float& y)
{
float temp=x; Output:
x=y;
y=temp;
}
By: Haylemaryam G. (MSc in ECEg.) 25
Exercise 1:
void 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;
}
Output ?
By: Haylemaryam G. (MSc in ECEg.) 26
Exercise 2:
void new(int, int&);
int main()
{
int a=22, b=44;
cout<< "a= "<<a<<",b = "<<b<<endl;
new(a,b);
cout<<"a = "<<a<<",b = "<<b<<endl;
new(2*a-3,b);
cout<<"a = "<<a<< ",b = "<<b<<endl;
}
void new(int x, int& y)
{
x=88;
y=99;
} Output ?
By: Haylemaryam G. (MSc in ECEg.) 27
Answers:
1) 2)

By: Haylemaryam G. (MSc in ECEg.) 28


Conclusion

By: Haylemaryam G. (MSc in ECEg.) 29


Function Overloading
➢ Means defining functions having the same name but that take different
parameters.
➢ Are functions with the same name having:
▪ Different number of argument
▪ Different type of argument or
▪ Both

By: Haylemaryam G. (MSc in ECEg.) 30


Example 1:
#include<iostream>
using namespace std;
int divide(int a, int b)
{
return (a/b);
}
float divide(float a, float b)
{
return(a/b);
}
int main()
{ Output
int x=5, y=2; float n=5.0, m=2.0;
cout<<divide(x,y); cout<<"\n";
cout<<divide(n,m);
return 0;
}
By: Haylemaryam G. (MSc in ECEg.) 31
Example 2:
#include<iostream>
using namespace std;
int addition (int a, int b)
{

int r;
r = a+b;
return (r);
}
int addition (int a, int b, int c)
{
int r;
r = a+b+c;
return (r);
}
int main ()
{ Output
int z; float y;
z = addition (5,3);
y = addition (5.5,3);
cout<<"The result is "<<z;
return 0;
}
By: Haylemaryam G. (MSc in ECEg.) 32
Default Argument
➢ Default argument is a programming convenience which removes the
burden of having to specify argument values for all function parameters.
➢ This is the function without argument.
➢ The default value of the argument is specified in the function prototype
/declaration.
➢ The default arguments are passed to the function if the argument is
missing on the function call.
➢ The arguments are default from right to left.

By: Haylemaryam G. (MSc in ECEg.) 33


Example 1:
#include<iostream>
using namespace std;
int AreaCube(int length, int width = 25, int height = 1);
int main()
{
int length = 100, width = 50, height = 2, area;
area = AreaCube(length, width, height);
cout<<"First area equals: "<<area<<"\n";
area = AreaCube(length, width);
cout<<"Second time area equals: "<<area<<"\n";
area = AreaCube(length);
cout<<"Third time area equals: "<<area<<"\n";
return 0;
}
int AreaCube(int length, int width, int height) Output
{
return (length*width*height);
}
By: Haylemaryam G. (MSc in ECEg.) 34
Example 2: Output
#include<iostream>
using namespace std;
int divide(int a, int b=2)
{
int r;
r = a/b;
return(r);
}
int main() N.B
{ ➢ Though the 2nd parameter is not
cout<<divide(12); specified when calling function
cout<<endl; “divide” it takes the 2nd value of
cout<<divide(20,4); divide function that is found @
return 0; function prototyping i.e. the
} default value in argument.
By: Haylemaryam G. (MSc in ECEg.) 35
Inline Function
➢ Inline Functions are extended when they are called or invoked.
➢ Function declared with inline, the compiler copies the code from the inline
function directly into the calling function.
Syntax:
inline datatype function_name(parameters)
{
statements;
}

➢ This tells the compiler to replace each call to the function with explicit code
for the function. Use it only for very short functions.
By: Haylemaryam G. (MSc in ECEg.) 36
Example 1:
//actually be compiled as though it were //this
#include<iostream> program:
using namespace std;
inline int cube(int x) #include<iostream>
{
return x*x*x; using namespace std;
} int main()
int main() {
{ cout<<(4)*(4)*(4)<<endl;
cout<<cube(4)<<endl; int x, y;
int x,y;
cin>>x;
cin>>x;
y = cube(2*x-3); y = (2*x+3)*(2*x+3)*(2*x+3);
} return 0;
}

By: Haylemaryam G. (MSc in ECEg.) 37


Recursive Functions: is function that calls themselves.
Example:
#include<iostream>
using namespace std;
long factorial (long a)
{
if(a>1)
return (a*factorial(a-1));
else
return 1;
}
int main()
{
long x;
cout<<"Type a number:"; Output
cin>>x;
cout<<x<<"!"<<"="<<factorial(x);
return 0;
}
By: Haylemaryam G. (MSc in ECEg.) 38
Exercise_1: //Program to find out the prime numbers from a given range.
#include<iostream>
using namespace std;
int prime(int, int);
int main()
{ count = 0;
int st, en; for (j=1; j<=i; j++)
cout<<"Enter the start value ="; {
cin>>st;
cout<<"Enter the end value ="; count=0;
cin>>en; for (j=1; j<=i; j++)
prime(st, en); if(i%j==0)
return 0; count = count+1;
} }
prime(int st, int en) if(count==2)
{ cout<<i<<endl;
int i, j, count; }
for (i=st; i<=en; i++) }
{
By: Haylemaryam G. (MSc in ECEg.) 39
Exercise_2: //Program to find out the raise to power of given number by recursion.
#include<iostream>
using namespace std;
int fun(int, int);
int main ()
{
int a, b, res;
cout<<"Enter the base of number = "; cin>>a;
cout<<"Enter the power of base = "; cin>>b;
res = fun(a,b);
cout<<"The raise to power is = "<<res;
return 0;
}
fun(int a, int b)
{
int res;
if(b==0)
return (1);
else
res = a*fun(a,(b-1));
return (res);
}
By: Haylemaryam G. (MSc in ECEg.) 40
Answers: Outputs:

1) 2)

By: Haylemaryam G. (MSc in ECEg.) 41


Any Questions?
END !

By: Haylemaryam G. (MSc in ECEg.) 42

You might also like