0% found this document useful (0 votes)
2 views40 pages

C++ chapter 2

Uploaded by

akliluasebot
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)
2 views40 pages

C++ chapter 2

Uploaded by

akliluasebot
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/ 40

Basic computer programming II

Chapter 2
Function in C++
Compiled by: Desiyalew Haregu
@CCI, WKU, 2014 EC.

Compiled By: Desiyalew H. @2014 1


Basic concept and need of function
What is a function?
Functions are like building blocks or
Is a group of statements that together perform a task.
Associate a sequence of statements (the function body) with a name .
A function is a named block of code that perform some action.
The statement written in function are executed when it is called by its name.
Each function has a unique name.
Function are the building block of C++ programs.
They are used to perform the tasks that are repeated many times
Functions may have zero or more function parameters .
Functions can be invoked using a function-call expression which initializes the
parameters from the provided arguments .

Compiled By: Desiyalew H. @2014 2


Basic concept and need of function
What is a function? (cont.)
You may define your own functions in C++.
Using functions can have many advantages, including the following:
You can reuse the code within a function.
You can easily test individual functions.
If it's necessary to make any code modifications, you can make
modifications within a single function, without altering the program
structure.
You can use the same function for different inputs.
Every valid C++ program has at least one function - the main()
function.

Compiled By: Desiyalew H. @2014 3


Basic concept and need of function
Why function?
Used to divide a large code into module. Due to this we can easily debug and
maintain the code.
Avoid repetition of code
Increase program readability
Divide a complex problem into simpler one.
Reduce chance of error
Makes modifying a program becomes easier
Makes unit testing possible

Compiled By: Desiyalew H. @2014 4


Basic concept and need of function
Function Basics
One of the best ways to tackle a problem is to start with the overall goal,
then divide this goal into several smaller tasks.
You should never lose sight of the overall goal, but think also of how
individual pieces can fit together to accomplish such a goal.
If your program does a lot, break it into several functions. Each function
should do only one primary task.

Compiled By: Desiyalew H. @2014 5


Basic concept and need of function
Summarized function basics
C++ functions generally adhere to the following rules.
1. Every function must have a name.
2. Function names are made up and assigned by the programmer following the
same rules that apply to naming variables. They can contain up to 32 characters,
they must begin with a letter, and they can consist of letters, numbers, and the
underscore (_) character.
3. All function names have one set of parenthesis immediately following them.
This helps you (and C++ compiler) differentiate them from variables.
4. The body of each function, starting immediately after parenthesis of the
function name, must be enclosed by braces.

Compiled By: Desiyalew H. @2014 6


Basic concept and need of function
Types of Functions
Depending on whether a function is predefined or created by
programmer, there are two types of function:
Library functions(Predefined functions)
User defined functions

Compiled By: Desiyalew H. @2014 7


Basic concept and need of function
Library functions(Predefined functions)
are part of compiler package.
Part of standard library made available by compiler.
Can be used in any program by including respective header file.

Compiled By: Desiyalew H. @2014 8


Basic concept and need of function
User defined functions
Created by user or programmer.
Created as per requirement of the program.

Compiled By: Desiyalew H. @2014 9


Declaring, defining and calling function
Declaring function
Function declaration is the model of a function.
It is also known as Function Prototype.
It provides information to compiler about the structure of function to
be used in program. It ends with semicolon (;).
It consists of:
Function name
Function return type
Numbers & types of parameters

Compiled By: Desiyalew H. @2014 10


Declaring, defining and calling function
Declaring function
Syntax: Return-type Function-name (parameters);

Parameters are the values


Indicates the types Indicates the that are provided to a
name of function function when the function
of value that will be is called.
returned by function

Compiled By: Desiyalew H. @2014 11


Declaring, defining and calling function
Declaring function
Syntax: Return-type Function-name (parameters);
Examples:
Int add(int, int);
void add(void);
Int add(float, int);

Compiled By: Desiyalew H. @2014 12


Declaring, defining and calling function
Defining function
A set of statements that explains what a function does is called FUNCTION
Definition.
A function definition consists of two parts: interface (prototype) & body.
The brace of a function contains the computational steps (statements) that
computerize the function.
The definition consists of a line called the decelerator.
If function definition is done before the main function, then there is no need to put
the prototype, otherwise the prototype should be scripted before the main function
starts.

Compiled By: Desiyalew H. @2014 13


Declaring, defining and calling function
Defining function
A function definition can be written at:
 Before main() function
 After main() function
 In a separate file

Syntax:
Return-type Function-name (parameters) function header

{ statement 1;
statement 2;

:
: Function body
:
statement N;
Compiled By: Desiyalew H. @2014 14
}
Declaring, defining and calling function
Defining function
Example:

Compiled By: Desiyalew H. @2014 15


Declaring, defining and calling function
Function Call
The statement that activates a function is known as FUNCTION CALL.
The following steps take place when a function is called:
1. The control moves to the function that is called.
2. All statements in function body are executed.
3. Control returns back to calling function.

Compiled By: Desiyalew H. @2014 16


Declaring, defining and calling function
Function Call Int sum()
{ int x=5;
Syntax:
Int sum=0;
#include<iostream>
Sum=sum +x; Function definition
using namespace std;
Cout<<sum;
int sum();
Return 0;}
int sum(int x);
Declaration/ Int Sum (int x)
void student(); prototyping
{…..}
int main()
Void student()
{
{…….}
Sum();
Sum(x); function calling
Student(): } Compiled By: Desiyalew H. @2014 17
Scope of Functions
Scope of Functions
Area in which a function can be accessed is known as SCOPE OF FUNCTION.
 These are two types:
1. Local Function
 A function that is declared in another function is called Local Function.
2. Global Function
 A function that is declared outside any function is called Global Function.

Compiled By: Desiyalew H. @2014 18


Function categories
1. Function with no return value and no argument.
void add(void);
2. Function with arguments passed and no return value.
void add(int, int);
3. Function with no arguments but returns a value.
int add(void);
4. Function with arguments and returns a value.
int add(int, int);

Compiled By: Desiyalew H. @2014 19


Function categories
1. Function with no return value and no argument.
void add(void);
Example: #include<iostream>
using namespace std;
void main()
{ void display(void); //fun declaration
display(); // fun calling
return 0; }
void display()
{ cout<<"function with no return value and argument"<<endl;}
Compiled By: Desiyalew H. @2014 20
Function categories
2. Function with arguments passed and no return value.
void add(int, int);
Example: #include<iostream>
using namespace std;
Void add(int , int);
Int main()
{ int a,b;
Cin>>a>>b;
add(a,b); // function calling
Return 0;}
Void add(int x, int y)
{ int sum;
Sum=x+y;
Compiled By: Desiyalew H. @2014 21
Cout<<sum;}
Function categories
3. Function with no arguments but
returns a value.
int add(void);
Example: #include<iostream> int add(void)
using namespace std; {
int main() int a, b;
{ cin>>a>>b;
int add(void); return (a+b);
int sum; }
sum=add();
cout<<sum;
return 0;
}
Compiled By: Desiyalew H. @2014 22
Function categories
4. Function with arguments and returns a value.
int add(int, int);
Example: #include<iostream>
using namespace std;
int main()
{
int sqr(int);
int a, result;
cin>>a;
result=sqr(a);
cout<<result;
}
int sqr(int x)
{
return (x*x);
}
Compiled By: Desiyalew H. @2014 23
Types of Function calling
Call by Value Call by Reference
Call by value passes the value of actual Call by reference passes the address of
parameter to formal parameter. actual parameter to formal parameter.
Actual & formal parameter refer to Actual & formal parameter refer to
different memory location. same memory location.
It requires more memory. It requires less memory.
It is less efficient. It is more efficient.

Compiled By: Desiyalew H. @2014 24


Function calling by value example
#include <iostream> // function definition to swap the values.
using namespace std; void swap(int x, int y) {
// function declaration int temp;
void swap(int x, int y); temp = x; /* save the value of x */
int main () { x = y; /* put y into x */
// local variable declaration: y = temp; /* put x into y */
int a = 100; return;
int b = 200; }
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
// calling a function to swap the values.
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
Compiled By: Desiyalew H. @2014 25
Function calling by reference example
#include <iostream>
using namespace std;
void swap(int *x, int *y)
{
int swap;
swap=*x;
*x=*y;
*y=swap;
}
int main()
{
int x=500, y=100;
swap(&x, &y); // passing value to function
cout<<"Value of x is: "<<x<<endl;
cout<<"Value of y is: "<<y<<endl;
return 0;
}

Compiled By: Desiyalew H. @2014 26


Difference between call by value and call by reference in C++
Call by value  An address of value is passed to the function
 A copy of value is passed to the function  Changes made inside the function is reflected outside
the function also
 Changes made inside the function is not
 Actual and formal arguments will be created in same
reflected on other functions memory location
 Actual and formal arguments will be created #include<iostream.h>
in different memory location #include<conio.h>
Int main()
{
Int a=100;
Int &ref=a;
cout<<“value of a is”<<a;
cout<<“value of ref is”<<ref;
Output:
cout<<address of a is”<<&a;
cout<<address of a is”<<&ref;
100
Return 0; 100
} 0012dcD2
0012dcD2
Call by reference

Compiled By: Desiyalew H. @2014 27


Scope of variable
Local Variable Global Variable
Local variables are declares within a Global variables are declares outside
function. any function
It can be used only in function in which Global variables can be used in all
they declared. function.
Local variable are destroyed when Global variable are destroyed when the
control leave the function. program is terminated.
Local variables are used when the vales Global variables are used when values
are to be used within a function. are to be shared among different
functions.
A local variable declared with keyword
STATIC is called STATIC VARIABLE.
It is used to increase the lifetime of
Compiled By: Desiyalew H. @2014 28
local variable.
Scope of variable
#include <iostream>
Using namespace std; Scope Operator
 local scope overrides the global scope, having a
Int fun(); local variable with the same name as a global
Int main() variable makes the latter inaccessible to the local
scope.
{ int I;  The global num1 is inaccessible inside fun1(),
for( i=0;i<=5;i++) because it is overridden by the local num1
parameter.
fun();  This problem is overcome using the scope
operator „::‟ which takes a global entity as
return 0; } argument.
Int fun() int num1 = 2;
void fun1(int num1)
{ static int n=0; // local variable which is {
static. num1=33;
n++ cout<<num1; // the out put will be 33
cout<<::num1; //the out put will be 2 which is the global
cout<<“value of n =“<<n<<endl; }
}
Compiled By: Desiyalew H. @2014 29
Function Overloading
 The process of declaring multiple functions with same name but different parameters is called
FUNCTION OVERLOADING.
 The function with same name must differ in one of the following ways:
 Numbers of parameters
 Type of parameter
 Sequence of parameters

Example :
// same name different arguments
int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }
 Here, all 4 functions are overloaded functions.
 Notice that the return types of all these 4 functions are not the same.
Compiled By: Desiyalew H. @2014 30
Function Overloading
 Overloaded functions may or may not if (var < 0.0)
have different return types but they var = -var;
must have different arguments. For return var;
example, }
// Error code // function with int type parameter
int test(int a) { } int absolute(int var) {
double test(int b){ }
if (var < 0)
 Here, both functions have the same var = -var;
name, the same type, and the same return var;
number of arguments. Hence, the }
compiler will throw an error. int main() {
// Program to compute absolute value // call function with int type parameter
// Works for both int and float/Overloading Using Different cout << "Absolute value of -5 = " <<absolute(-5) << endl;
Types of Parameter // call function with float type parameter
#include <iostream> cout << "Absolute value of 5.5 = " << absolute(5.5f) <<
using namespace std; endl;
// function with float type parameter return 0;
Compiled By: Desiyalew
} H. @2014 31
float absolute(float var){
Default Arguments in C++ Functions
The default arguments are used cout<<sum(1)<<endl;
when you provide no arguments or /* In this case a value is passed as
only few arguments while calling a * 1 and b value as 2, value of c values is
* taken from default arguments.
function. */

The default arguments are used cout<<sum(1, 2)<<endl;


during compilation of program.. /* In this case all the three values are
* passed during function call, hence no
example: * default arguments have been used.
#include <iostream> */

using namespace std; cout<<sum(1, 2, 3)<<endl;


int sum(int a, int b=10, int c=20); return 0;
int main() }
{ int sum(int a, int b, int c){
/* In this case a value is passed as int z;
* 1 and b and c values are taken from z = a+b+c;
* default arguments. return z;
*/ }
Compiled By: Desiyalew H. @2014 32
Default Arguments in C++ Functions
Valid: Following function  int sum(int a, int b=20, int c);

declarations are valid /* Since a has default value assigned, all the
 int sum(int a=10, int b=20, int c=30); * arguments after a (in this case b and c) must
 int sum(int a, int b=20, int c=30); have
 int sum(int a, int b, int c=30); * default values assigned, b has default value but
* c doesn't have, thats why this is also invalid
 Invalid: Following function declarations */
are invalid  int sum(int a=10, int b=20, int c);
/* Since a has default value assigned, all the
* arguments after a (in this case b and c) must
have
* default values assigned
*/
 int sum(int a=10, int b, int c=30);
/* Since b has default value assigned, all the
* arguments after b (in this case c) must have
* default values assigned
*/ Compiled By: Desiyalew H. @2014 33
Recursive Functions
Recursive function can be defined as a routine that calls itself directly
or indirectly.
 The process may repeat several times, outputting the result and the end
of each iteration.
Syntax:
recursionfunction()
{
recursionfunction(); //calling self function
}

Compiled By: Desiyalew H. @2014 34


Recursive Functions
Example: Direct recursion if(n<0)
return(-1); /*Wrong value*/
#include<iostream>
if(n==0)
using namespace std;
return(1); /*Terminating condition*/
int main()
else
{
{
int factorial(int);
return(n*factorial(n-1));
int fact, value;
}
cout<<"Enter any number: ";
cin>>value;
} Factorial equation:
F(n)=n*f(n-1)
fact=factorial(value);
cout<<"Factorial of a number is: "<<fact<<endl;
return 0;
}
int factorial(int n)
{ Compiled By: Desiyalew H. @2014 35
Recursive Functions
Indirect recursion:
When function calls another function and that function calls the calling
function, then this is called indirect recursion.
For example:
 function A calls function B and Function B calls function A.

Compiled By: Desiyalew H. @2014 36


Recursive Functions
Example: Indirect recursion return n*fa(n-1);
}
#include <iostream>
int main(){
using namespace std;
int num=5;
int fa(int);
cout<<fa(num);
int fb(int);
return 0;
int fa(int n){
}
if(n<=1)
return 1;
else Factorial equation:
F(n)=n*f(n-1)
return n*fb(n-1);
}
int fb(int n){
if(n<=1)
return 1;
else Compiled By: Desiyalew H. @2014 37
Inline Function
The inline functions help to increase the execution time of a program.
The programmer can make a request to the compiler to make the function as
inline.
Making inline means that compiler can replace those function definitions on the
place where they are called.
The compiler replaces the definition of inline functions at compile time instead of
referring function definition at runtime.
Syntax: inline ret_type func_name(parameter_list) {
function body }
NOTE- This is just a suggestion to the compiler to make the function inline and it
totally depends on the compiler to whether make it as inline or not. If a function is
big, then the compiler can ignore the “inline” request and treat the function as a
normal function.
Compiled By: Desiyalew H. @2014 38
Inline Function
#include<iostream> #include<iostream>
using namespace std; using namespace std;
int cube(int x) inline int cube(int x)
{ {
int result=x*x*x; Response int result=x*x*x;
return result; return result;
} }
int main() int main()
{ int x=2; //no need to request the inline function
int x=2; Request cout<<cube(x); int result=x*x*x; return result;
cout<<cube(x);
} }
1. simple function 2. Inline function
Compiled By: Desiyalew H. @2014 39
Inline Function
Advantages of Inline Function in C++
Inline Function speed up your program because it avoids the time waste due to
function calling and response back.
Inline Function increases locality of reference by utilizing instruction cache.
Disadvantages of Inline Function in C++
When we inline the function, it is resolved at compile time. So, we can say that if
you change the code of the inline function, then it is necessary to recompile all the
programs to make sure that it is updated.
As mentioned above it increases the executable size, which may cause thrashing in
memory. More number of page fault bringing down your program performance.
Sometimes not useful for example in an embedded system where large executable
size is not preferred at all due to memory constraints.
Q. Where Inline Function will not work?
Compiled By: Desiyalew H. @2014 40

You might also like