0% found this document useful (0 votes)
17 views61 pages

Chapter 5 - Function

Chapter Five discusses the concept of functions in C++ programming, emphasizing their role in modular programming and code reusability. It explains the types of functions, including standard library functions and user-defined functions, and outlines the structure of function declarations, calls, and definitions. Additionally, it covers variable scope, local and global variables, and parameter passing methods such as call by value and call by reference.

Uploaded by

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

Chapter 5 - Function

Chapter Five discusses the concept of functions in C++ programming, emphasizing their role in modular programming and code reusability. It explains the types of functions, including standard library functions and user-defined functions, and outlines the structure of function declarations, calls, and definitions. Additionally, it covers variable scope, local and global variables, and parameter passing methods such as call by value and call by reference.

Uploaded by

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

CHAPTER FIVE:

FUNCTIONS IN C++ PROGRAMMING


Functions
 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.
 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
Advantages of A Function
 Support for modular programming
 Reduction in program size.
 Code duplication is avoided.
 Code reusability is provided.
 Functions can be called repetitively.
 A set of functions can be used to form libraries.
 Experience has shown that the best way to develop and
maintain large programs is to construct it from smaller
pieces (Modules)
 The techniques is Called “Divide and Conquer “
main () main ()
{ {
-------------- --------------
-------------- --------------
-------------- }
-------------- Function f1()
-------------- {
Bad Development Wise Development
-------------- --------------
approach approach
-------------- --------------
-------------- }
-------------- Function f1()
-------------- {
-------------- --------------
-------------- --------------
}
return 0; Function f1()
} .
.
Types of Functions

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>
C++ Library Functions

6
User defined Functions

• Every C++ Program has a main function


(Boss ) the caller /Calling function
Notes:- • Every C++ Program starts in the main function and ends in the main
function
• Usual main calls other functions But other functions call each other
Function is divided into
three
parts
 Function Declaration/Prototypes
 Function Call
 Function Definition
Function Prototypes(Function Declaration)
• 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.
9
Contd…
• E.g.

• float AddTwoNumbers(int a, int b);

• 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.

10
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();

11
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 :

12
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;
}
Example 1
#include <iostream>
using namespace std;
void greet() --------------------------------------- //3rd
{
cout << "Hello there!"; ---------------------------//4th
}
int main() -------------------------------------------//1st
{
greet(); -------------------------------------------//2nd
return 0; ------------------------------------------//5th
}
Example 2
#include<iostream>
using namespace std;
Function prototyping
float AddTwoNumbers();
int main()
{
float x;
Function calling
x=AddTwoNumbers();
cout<<“a+b=”<<x;
return 0;
}
Function definition
float AddTwoNumbers()
{
float a=2.5;
float b=7.5;
float c=a+b;
return c;
}
Example 3

#include< iostream>
using namespace std;
int sum (int x, int y); //declaring the function
int main()
{
int a = 10;
int b = 20;
int c = sum (a, b); //calling the function
cout << c;
}
int sum (int x, int y) //defining the function
{
return (x + y);
}
#include <iostream>
Example 4 on tion
cti nc
fu n fu
Using namespace std; , ain
le d
int add(int, int); //function declaration or prototypingncel ore m
s ca bef
int main() n i e
tio com
{ ar a to
ecl as
int a,b; I f d nh
. B: nitio
cout<<"Enter Two integers"<<endl; N efi
d
cin>> a >> b;
cout<<“Sum"<<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;}
#include<iostream>
Example 5
using namespace std;
float AddTwoNumbers(float, float); prototype
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
}
Scope of Variables
 Scope: is the portion of a program where an identifier or a
variable name can be used
» Function-prototype scope

» File scope

» Block scope
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;
}
Local and Global Variables
• Local Variable: are variables defined inside a function or
inside a block
– They are known only to the function

– They cannot be used outside the function

– As the function finishes, the variables are destroyed

– So, they are redeclared/initialized in the next function call.

Local and Global Variables in C++ - Dot Net Tutorials


Cont’d…
• Global variables: is any variable defined outside all the functions in a program,
including main – main().

– Its scope is from variable definition to the end of the entire program

– All functions can access these variables.

• Inside a function or a block which is called


local variables,
• In the definition of function parameters which
is called formal parameters.
• Outside of all functions which are called
global variables.
I. Using Global Variables
#include <iostream>  When used as a function return

using namespace std; type, the void keyword specifies

int x = 0; that the function doesn't return a


value.
void f1()
 When used for a function's
{ x++;}
parameter list, void specifies that
void f2()
the function takes no parameters.
{ x+=4;  When used in the declaration of a
f1(); } pointer, void specifies that the
int main() pointer is "universal.“

{ f2();
25
cout << x << endl;}
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1()
x =0
{ x++;}
void f2()
{
x+=4;
f1();
}
int main()
{
f2();
cout << x << endl;
}
26
#include <iostream.h>
int x = 0;
void f1()
{ x 0
x++;
}
void f2()
{
x+=4; f1();
}
int main()
{ void main()
f2(); {
1 f2();
cout << x << endl; cout << x << endl ;
} }
27
#include <iostream.h>
int x = 0;
void f1()
{
x 0
4
x++;
}
void f2()
{
x+=4; f1(); void f2()
{
} 2 x += 4;
void main() f1();
}
{
void main()
f2(); {
cout << x << endl; 1 f2();
cout << x << endl ;
} }
28
#include <iostream.h>
int x = 0;
void f1()
{ x 5
4
x++;
void f1()
} {
void f2() 4 x++;
}
{
void f2()
x+=4; f1(); {
} x += 4;
3 f1();
void main() }
{
void main()
f2(); {
cout << x << endl; 1 f2();
cout << x << endl ;
} }
29
#include <iostream.h>
int x = 0;
void f1()
{
x 5
4
x++;
void f1()
} {
void f2() x++;
5 }
{
x+=4; f1(); void f2()
{
} x += 4;
void main() 3 f1();
}
{
void main()
f2(); {
cout << x << endl; 1 f2();
cout << x << endl;
} }
30
#include <iostream.h>
int x = 0;
void f1()
{ x 5
4
x++;
}
void f2()
{
void f2()
x+=4; f1(); {
} x += 4;
f1();
void main() 6 }
{ void main()
f2(); {
1 f2();
cout << x << endl; cout << x << endl;
} }
31
#include <iostream>
using namespace std;
int x = 0;
void f1()
x 5
4
{
x++;
}
void f2()
{
x+=4; f1();
}
void main()
void main()
{ {
f2(); f2();
7 cout << x << endl;
cout << x << endl;} }
32
#include <iostream.h>
int x = 0;
void f1()
{
x 5
4
x++;
}
void f2()
{
x+=4; f1();
}
void main()
{
void main()
f2(); {
cout << x << endl; f2();
cout << x << endl;
} 8 }
33
#include <iostream>
int x = 0;
void f1()
{
x++;
}
void f2()
{
x+=4; f1();
}
int main()
{
f2();
cout << x << endl;
}
34
Parameters Pass in a
Function
 Parameters Pass/Call by Value

 Parameters Pass/Call by Reference

 Return by Reference
Parameters Pass
Pass/Call by value Pass/Call by reference
 Copies of the arguments are  Pass by reference is the
created . second way of passing
 The parameters are parameters to the function.
mapped to the copies of  The address of the
the arguments created. argument is copied into the
 The changes made to the parameter.
parameter do not affect  The changes made to the
the arguments. parameter affect the
arguments.
 It uses & symbol for
representation

36
Argument passing By Argument passing By
Value Reference
We call function addition passing We call function addition passing

the values of x and y, that the references of x and y, that

means 5 and 3 respectively, means 5 and 3 respectively, not

not the variables themselves. the values.


Example on Argument Passing by reference
#include<iostream> en
w h
using namespace std; de
co lue
void duplicate( int &a,int &b,int &c) is va
h
t by
{a*=2; g
in ed
nn s s
b*=2; Ru pa
by is
c*=2;} ck ent
h e m
int main()
e C rgu
as ea
{ e th
Pl
int x=1,y=3,z=7;
duplicate(x,y,z);
cout<<"x="<<x<<" "<<"y="<<y<<" "<<"z="<<z;
return 0;
}
#include<iostream> #include<iostream>
using namespace std; using namespace std;
void value( int x); By Value void value( int &x); By Reference
int main() int main()
{ int x=10; {int x=10;
cout <<"before change is "<<x <<endl; cout <<"before change is "<<x <<endl;
value(x); value(x);
cout <<"after change is “<< x<<endl;; cout <<"after change is “<< x<<endl;;
return 0; return 0;
} }
void value (void x) void value (int &x)
{ {
x=0; x=0;
cout <<"function value is "<<x<<endl;; cout <<"function value is "<< x<<endl;;
} } Before change is 10
Before change is 10
function value is 0 function value is 0
After change is 10 After change is 0
#include<iostream>
using namespace std; Example on Argument Passing
int add(int n); by value
int main()
{ int number,result;
number=5;
cout << " The initial value of number : " << number << endl;
result=add(number);
cout << " The final value of number : " << number << endl;
cout << " The result is : " << result << endl;
return(0);
}
int add(int number)
{
number=number+100;
return(number);}
#include<iostream> //example two
using namespace std;
int add(int &number);
int main ()
{
int number;
int result;
number=5;
cout << "The value number before calling : " << number << endl;
result=add(number);
cout << “The value after the it is returned : " << number << endl;
cout << "The value of result : " << result << endl;
return(0);}
int add(int &p)
{ p=p+100;
return p; }
Returning More than one value
//More than one returning value
#include<iostream>
using namespace std;
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
Cont…
Inline functions
Default arguments
Function overloading
Inline Functions
An inline function is a function that
expanded in line when it is invoked.
That is the compiler replaces the function
call with the corresponding function code .
Syntax:
inline function-header
{
Function body
}
inline functions
• The inline directive can be included before a function
declaration to specify that the function must be
compiled as code in the same point where it is called.

Syntax: inline type name ( arguments ... )


{
//Body goes here
}
Default Arguments
Default values are specified when the function
is declared.
Compier looks at the prototype to see how
many arguments the function uses.
Default arguments are useful in situations
where some arguments always have the same
value.
Default values in Arguments
#include<iostream>
N.B
using namespace std;
int divide(int a, int b=2) • Though the 2nd parameter is
{
int r; not specified when calling
r=a/b; function “divide” it takes the 2nd
return(r);
} value of divide function that is
int main() found @ function prototyping
{
cout<<divide(12); i.e. the default value in
cout<<endl; argument.
cout<<divide(20,4);
return 0;
}
//out put 6 and 5
Function Overloading
 A function is overloaded when same name is given to
different function.
 The two functions with the same name will differ at
least in one of the following.
a) The number of parameters
b) The data type of parameters
c) The order of appearance
Function Overloading
Means defining functions having the same name but that take different parameters
#include<iostream.h>
int divide(int a,int b)
{
return (a/b);
}
float divide(float a,float b) Function overloading
{
return(a/b);
}
Are functions with the same
int main()
{
name having:
int x=5,y=2; float n=5.0,m=2.0;
cout<<divide(x,y);
Different number of
cout<<"\n"; argument
cout<<divide(n,m);
return 0;}  Different type of argument
Both
Example 1 Example 2
int addition (int a, int b) #include<iostream>
using namespace std;
{ int r; int addition (int a, int b)
r=a+b; {
int r;
return (r);} r=a+b;
float addition (float a, float b) return (r);}
int addition (int a,int b,int c)
{ float r; {
r=a+b; int r;
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;}
Exercise 1
#include<iostream>
using namespace std;
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(l,w);
cout<<"Area of the rectangle:"<<areaofrect<<endl;
return 0;
}
int area( int l,int w)
{
return l*w;}
Exercise 2:
#include<iostream>
using namespace std;
int AreaCube(int length,int width=5,int height=1);
int main()
{int width=2;
int height=3;
int area;
area = AreaCube(length, width, height);
cout<<"First area equals:"<<area<<"\n";
area = AreaCube(length, width);
cout<<"second area equals:"<<area<<"\n";
area = AreaCube(length);
cout<<"Third area equals:"<<area<<"\n";
return 0;}
AreaCube(int length, int width, int height)
{
return(length * width * height);
}
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);
}
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;}
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);
Example
#include <iostream>
using namespace std;
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " "<<endl;
}
int main()
{
int myArray[] = {1, 2, 3, 4, 5};
int arraySize=sizeof(myArray) / sizeof(myArray[0]);
printArray(myArray, arraySize);
return 0;
}
Exercise on functions
1. What are the differences between the function prototype and the function
definition?
 The function prototype declares the function; the definition defines it. The
prototype
 ends with a semicolon; the definition need not.
 The declaration need not include names for the parameters; the definition
must.

2. Do the names of parameters have to agree in the prototype, definition, and


call to the function?
 No: All parameters are identified by position and data type, not name.

3. If a function doesn’t return a value, how do you declare the function?


 Return to void
4. If you don’t declare a return value, what type of return value is assumed?
 By default returns int

57
5. What is a local variable?
 A local variable is a variable passed into or declared
within a block,
6. What is scope?
 Scope refers to the visibility and lifetime of local and
global variables.
 Scope is usually established by a set of braces.
7. What is recursion?
 Generally refers to the ability of a function to call itself.
8. When should you use global variables?
 typically used when many functions need access to the
same data.

58
Exercise on Array
1. What are the first and last elements in SomeArray[25]?
2. How do you declare a multidimensional array?
eg int Array[5][3];
3. Initialize the members of an array declared as SomeArray[2][3][2].
For example, SomeArray[2][3][2] is
a three-dimensional array. The first dimension has two elements, the
second has three, and the third has two.
3. SomeArray[2][3][2] = { { {1,2},{3,4},{5,6} }, {7,8},{9,10},{11,12}}};
4. How many elements are in the array SomeArray[10][5][20]?
5. How does a linked list differ from an array?
6. How many characters are stored in the string “Jesse knows C++”?
16 characters = 13 letters+2 space+one null char
7. What is the last character in the string “Brad is a nice guy”? Null
character

59
Exercise on loops

What is the value of x when the for loop completes?


for (int x = 0; x < 100; x++) //out of scope it has no valid value
1) Write a nested for loop that prints a 10×10 pattern of 0s.
for (int i = 0; i< 10; i++)
{
for ( int j = 0; j< 10; j++)
cout << “0”;
cout << endl;
}
2) Write a for statement to count from 100 to 200 by twos.
for (int x = 100; x<=200; x+=2)
3) .Write a while loop to count from 100 to 200 by twos.
int x = 100;
while (x <= 200)
x+= 2;
60
4. Write a do while statement to count from 100 to 200 by twos.
int x = 100;
do
{
x+=2;
} while (x <= 200);

4. Write a do...while loop to count from 100 to 200 by twos.


int x = 100;
do
{
x+=2;
} while (x <= 200);

C++ POINTERS (2020) - Introduction to C++ pointers (for beginners) PROGRAMMING TUTORIAL - YouTube

61

You might also like