0% found this document useful (0 votes)
28 views46 pages

Lecture 7

Uploaded by

fakhrialamqazi
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)
28 views46 pages

Lecture 7

Uploaded by

fakhrialamqazi
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/ 46

FUNCTIONS

LECTURE #7
FUNCTIONS
 A function is a subprogram, or module to which any amount of
data can be sent, which return only one value.

 A function is used to perform logically isolated task.

 It makes it easier to write programs and keep track of what they


are doing.

 It avoid rewriting the same series of instructions/statements


again and again.

 The instruction are written once, can be used at several places


in a program.
 Functions are not only used storing purpose, it also provides
the way of breaking the program into separate, short and well-
defined tasks.

 Each C++ program has at least one function, main( ), which is


automatically called where you execute the C++ program.

 Each function has its own name and when the name is
encountered, the function gets called i.e. the control is
transferred to the first statement in the called function.

 The function is completed until it executes the last statement


in the function.
A SIMPLE WITH A FUNCTION THAT RETURNS NO VALUE
#include<iostream. h>
#include<conio.h>
Void print(); //function prototype/declaration
Void main()
{

print(); //calling function


getch();
}
Void print() //function defination
{
Cout<<“Well come to the functions \n”;
return ;
}
 Return Type: A function may return a value. The return_type is
the data type of the value the function returns. Some functions
perform the desired operations without returning a value. In this
case, the return_type is the keyword void.

 Function Name: This is the actual name of the function. The


function name and the parameter list together represent the value of
the function.

 Parameters: When a function is called, you pass a value to the


parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number
of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters.

 Function Body: The function body contains a collection of


TYPES OF FUNCTIONS

1. Built-in functions
2. User-defined functions

 The type of functions that have already been


defined as a part of the language and can be used in
any program are called built-in functions.

 The built-in functions are provided for general use.


User defined functions

 The type of functions that are created by a user.

 These functions are written as a part of a program to


perform a specific task.

 A user defined function has three parts. These are:


 Function Declaration(prototype)
 Function Definition
 Function Calling
#include<iostream. h> Output:
Welcome to the main program
#include<conio.h>
Void funct( ); //function prototype Well come to the function subprogram
Void main( ) well come back to the main program
{
Cout<<“Welcome to the main program \n”;
Funct( ); //function call
Cout<<“well come back to the main program”;
getch( );
}
Void funct( ) //function defination
{
Cout<<“Well come to the function subprogram \n”;
Return ;
}
 The function used in this program is known as a
subroutine. A subroutine is a function that does not
return any values.

 Before defining function, it must be declared first.

 A function does not called until & unless being


declared.
FUNCTION DECLARATION(PROTOTYPE)
 Function declaration is also called prototype.

 The function declaration only provides the model of the


function.

 Function prototype is a statement, which must be end with a


semicolon (;).

 Function prototype consist of function return type,


function name, number and the type of parameters.

The general format of function declaration is as following:

Return_type function_name(type parameter, type


Examples:
Void funct();
The function return type is void. if a function does not
return a value, its return type will be void. i.e void
type specifies the empty set.

Void funct(void);
A function that has no parameter can use the reserved
word void in its parameter list.

int cube(int x);


Float area(int length, int width);
Float area (int, int)
FUNCTION DEFINITION
 The actual code of the function is called function definition.

 It consist of set of instruction/statements enclosed in block of


braces to perform a specific task.

 The function definition is always outside the main function.

 There is no semicolon after the closing braces.

Return_type function_name(type parameter, type parameter,


…..)
{
Body of the function;
A SIMPLE WITH A FUNCTION THAT RETURNS NO VALUE
#include<iostream. h>
#include<conio.h>
Void print(); //function prototype
Void main()
{

print();
getch();
}
Void print()
{
Cout<<“Well come to the functions \n”;
return ;
}
CALLING A FUNCTION
 Executing the statements of a function to perform a
task is called calling of the function

 A function is called by referencing the name of the


function.

 If the parameters of a function are available. then


mention the parameter after the name of the
function in the parenthesis.

 If function have no parameters then parenthesis are


left blank.
 When a function is called, the control shifts to the
function definition and the statements in the body of
the function are executed.

 After executing the statements in the body of the


functions, the control returns to the calling function
and the next statement comes immediately after the
function call is executed.
#include<iostream. h>
#include<conio.h>
Void sum(); //function prototype
Void main()
{

sum(); //function call


Cout<<“sum= “<<sum;
getch();
}
Void sum() //function definition
{
Int a ,b;
Cout<<“enter value for a and b \n”;
Cin>>a>>b;
return (a+b);
}
WRITE A PROGRAM IN C++ USING MULTIPLE FUNCTIONS IN A PROGRAM

#include <iostream.h> void italy( )


#include <conio.h> {
void italy();
cout<< "\nI am in italy" ;
void brazil();
void argentina();
}
int main() void brazil( )
{ {
cout<< "\nI am in main"; cout<<"\nI am in brazil" ;
italy( ) ; }
brazil( ) ;
void argentina( )
argentina( ) ;
cout<< "\n I am finally back in
{
main"; cout<< "\n I am in argentina" ;
getch(); }
return 0; Output:
PASSING ARGUMENTS TO FUNCTIONS
 If a function needs data to perform a specific task, this
data is provided through the arguments of the functions.

 The arguments are placed in parentheses.

 The arguments are either constants or variables.

 The parenthesis are written in same sequence in which


they are defined in the function declaration.

 The data type of an argument in the function call must


also match the corresponding data types in the function
declaration.
Void main() Sum(int x, int y, int z)
{ {
Sum(a, b, c); }
}
#include<iostream. h>
#include<conio. h>
Void sum(int, int);
Void main()
{
Clrscr();
Sum(10,15);
Cout<<“ok”;
getch();
}
Void sum(int x, int y)
{
int s;
S= x+y;
Cout<<“sum=”<<s<<endl;
}
WRITE A PROGRAM TO PASS TWO VARIABLES AS ARGUMENT TO
THE FUNCTION TO CALCULATE THEIR SUM AND PRINT ON SCREEN

#include<iostream. h> Sum(a,b);


#include<conio. h>
Cout<<“ok”;
Void sum(int, int);
getch();
Void main()
{ }
Int a , b; Void sum(int x, int y)
Clrscr(); {
Cout<<“enter 1st value ?”; int s;
Cin>>a; S= x+y;
Cout<<“enter 2nd value ?”; Cout<<“sum=”<<s<<e
Cin>>b; ndl;
}
WRITE A PROGRAM TO PASS A NUMBER AS ARGUMENT TO THE FUNCTION
BODY. PRINT THE TABLE OF THAT NUMBER IN THE FUNCTION BODY

#include<iostream. h> Void tab (int tt)


#include<conio. h>
{
Void tab(int);
Void main()
For(int c=1;c<=10;c++)
{ Cout<<c<<“ x”<<tt << “=“ <<
Clrscr(); c*tt;
cout<< endl;
int n;
}
Cout<<“enter any number”;
Cin>>n;
tab(n);
getch();
}
CALCULATE CUBE (X^3)
#include<iostream. h> }
#include<conio. h> int cube(int x)
Int cube (int , int ); {
Void main() return (x*x*x);
{ }
int n;
Cout<<“enter any
numbers”;
Cin>>n;
Cout<<“cube = ”<<cube
(n);
getch();
WRITE A PROGRAM TO CALL FUNCTION WHICH TAKES
TWO PARAMETERS NUM1 AND NUM2 AND RETURNS THE
MAXIMUM.

#include <iostream.h> int max(int num1, int num2)


#include <conio.h>
{
int max(int num1, int num2);
int main () if (num1 > num2)
{ result = num1;
int a = 100;
else
int b = 200;
int ret,result; result = num2;
return result;
ret = max(a, b); }
cout << "Max value is : " << ret <<
endl;
getch ( );
}
WRITE A FUNCTION TO CALCULATE THE FACTORIAL VALUE OF
ANY INTEGER ENTERED THROUGH THE KEYBOARD.

#include <iostream.h> int factorial ( int x )


#include <conio.h> {
int factorial(int x); int f = 1, i ;
int main() for ( i = x ; i >= 1 ; i-- )
{ f=f*i;
int a, fact ; return ( f ) ;
cout<< "\nEnter any number " ; }
cin>>a;
fact = factorial ( a ) ;
cout<<"Factorial value = "<< fact
;
getch();
}
WRITE A PROGRAM FOR CALCULATOR BY PASSING THREE ARGUMENTS
TO THE FUNCTION BODY. FIRST FOR NUMERIC, 2ND FOR ARITHMETIC
OPERATOR AND THIRD FOR OTHER NUMERIC NUMBER. PERFORM
ARITHMETIC OPERATION ON THE GIVEN NUMBERS AND PRINT THE
RESULT ON THE SCREEN
#include <iostream.h> Void cal(int x, char op, int y)
#include <conio.h> {

Void cal (int, char, int); Switch(op)


{
int main()
Case ‘+’:
{
Cout<<x + y;
Int n1,n2;
break;
Char op; Case ‘-’:
Cout<<“enter 1st value”; Cout<<x - y;
Cin>>n1; break;
Cout<<“enter 2nd value”; Case ‘*’:
Cin>>n2; Cout<<x * y;
Cout<<“enter operator”; break;
Cin>>op; Case ‘/’:
Cout<<x / y;
Cal(n1,op,n2);
break;
getch();
default:
}
LOCAL AND GLOBAL
VARIABLES
 The variables can be declared inside the main
function, inside user defined functions or outside
the main function.
 The effect of the variables declared in these places
is different.
 Based upon their effects , variables are divided
into two classes.

 Local Variables
 Global variables
LOCAL VARIABLES
 The variables that are declared inside the main function or
inside any user defined function are called local variables.

 These variables are also called automatic variables.

 The keyword “auto” can be used to declare these variables.

 For example,
auto int a,b,c;

The keyword “auto” is optional the variables used inside the


function are automatic by default.
LIFE TIME OF LOCAL
VARIABLES
 The lifetime of a variable is the time periods between the creation
and destruction of the variable.

 A variable remain available and can be used only during its lifetime.

 When the control is transferred to a function, the local variables or


variables declared inside the function are automatically created and
they occupy memory space to store data.

 When the control returns to the calling function or calling program,


the variables can only be accessed from within the function in which
they are declared.

 They are not available outside that function.


HOW TO USE LOCAL
VARIABLES
#include<iostream. h> int sum (int x, int y)
#include<conio. h> {
Void main() int sum (int x, int y)
{ {
int a,b,s; int rs;
int sum(int, int); rs = x + y;
return rs;
a=10; }
b=100;
s=sum(a, b);
Cout<<“sum=”<<s;
Cout<<“ok”;
}
 In the above program a, b and s are declared in the
main function. these are local variables for the main
function.

 The variables declared in the “sum” function are x, y


and rs. These variables declared in the function
declarator are also treated as local variables.
GLOBAL VARIABLES
 The variables that are declared outside the main function or any
other function are called global variables or external variables.

 These variables can be accessed in any function at any time during


execution of the program.

 The variables are used, when variables are need to be accessed by


more than one function in a program.

 The global are not normally used in a program because:


1. These variables can be accessed by all function, so it is difficult
to track changes in their values.
2. Occupy large amount of memory permanently during program
execution and data accessing speed of the program becomes slow.
LIFE- TIME OF GLOBAL VARIABLES
 The global variables exist in the memory throughout
the program execution.

 They are created into the memory when the program


execution starts.

 They are destroyed only when the program ends.

 Therefore, the lifetime of the global variables is


between the starting and the termination of the
program.
A PROGRAM CONSIST OF BOTH LOCAL AND GLOBAL VARIABLES
# include <iostream. h>
# include<conio. h>
int a, b, s; a, b, s; are Global variables, used
Void main() outside the main function.
These can be accessed by sum function
{ as well as the main function.
Void sum(int, int);
The x, y are local variables of function
a= 10; “SUM”
b=100;
sum(a, b);
cout<<“sum=”<<s;
cout<<“ok”;
}
void sum (int x , int y)
{
s= x+y;
LOCAL AND GLOBAL FUNCTION
 The function that are declared inside the main function or inside
any other function are called local functions. These can be called
only in that function in which they are declared.

 The function that are declared outside the main function are
called global functions. They can be called by any function.

 The function prototype defined in the header file are treated as


global function because they can be handled in any function.
AUTOMATIC & STATIC VARIABLES
 All local variables are automatic by default.
 To declare automatic variables we are using a keyword “Auto” in front of variable.
 Keyword “Auto” is optional.

auto int age;


auto float pay;
auto char name;

 All local variables are automatic & all global variable are static.

 Static numbers are special that are declared inside a function by using the keyword
“static”.

static float sum;


static int a;

.
 Static variables allows the last value of the variable to be
preserved, when its function ends. When the function is called
again, this preserved value can be used again.

 When a static variable is not initialized, the default value is


zero. When a function is called for the first time, this
initialization is made, on second call and after, this
initialization is not considered. It means that initialization is
made only the first time a function executes.

 Like local variables, these can only be accessed in the function


which are declared but they remain in existence for the lifetime
of the program
# include <iostream. h>
# include<conio. h>
Void main()
Output
{
int i; 10
int temp (int); 20
60
For(i=1;i<=3; i++)
{
Cout<< temp (i)<<endl ;
}
Cout<<“ok”;
}
int temp (int x)
{
Static int ;
Co=co*x;
return(co);
}
# include <iostream. h> Void aut (void)
# include<conio. h> {
Void aut (void); Auto int c=0;
Void main() c++;
Cout<<c<<endl;
{
return;
int n;
}
For(n=1; n<=5;n++)
aut(); Output:
getch(); 1
} 1
1
1
1
# include <iostream. h> Void stat(void)
# include<conio. h> {
Void stat(void); Static int c=0;
Void main() c++;
{ Cout<<c<<endl;
int n; return;
For(n=1; n<=5;n++) }
stat();
getch(); Output:
} 1
2
3
4
5
REFERENCE PARAMETERS
 There are two ways to pass arguments to a function. These are :

 Arguments passed by value


 Arguments passed by reference

 When an arguments is passed by value to a function a new variable of the


data type of the arguments is created and the data is copied into it.

 The function accesses the value in the newly created variable and the data in
the original variable in the calling function is not changed.
 The data can also be passed to a function by reference of a variable
name that contains data. The reference provides the second name for
a variable name. when a variable is passed by reference to a function.

 No new copy of the variable is created. Only the address of the


variables is passed to the function.

 The original variable is accessed in the function with reference to its


second name.

 Both variables use the same memory location. Thus any change in
the reference variable also change the value in the original variable.

 The reference parameter are indicated by an ampersand (&) sign


after the data type both in the function prototype and in the function
definition.
WRITE A PROGRAM TO EXCHANGE THE VALUES OF TWO
VARIABLES BY USING REFERENCE ARGUMENTS IN THE
FUNCTION
# include<iostream. h> Cout<<“value for B=”<<b;
#include<conio. h> cout<<endl;
Void main() Cout<<“OK”;
{ }
Void exch (int &, int &); Void exch (int& x, int & y)
Int a,b; {
Cout<<“enter value for A”; int t;
Cin>>a; t=x;
Cout<<“enter value for B”; x=y;
Cin>>b; Y=t;
exch(a,b); }
Cout<<“values after exchange” ;
cout<<endl;
Cout<<“value of A =”<<a<<endl;
}
RECURSION
 One of the most important features of c++ is recursion.

 Recursion is the ability of a function through which a


function can call itself.

 While writing a Recursive function. It is essential that the


function include some terminating condition.

 Condition prevents the recursion from continuing


indefinitely.
PROGRAM FOR RECURSIVE FUNCTION TO
COMPUTE X TO POWER Y(X^3)
#include<iostream. h> Int power(int x,int y)
#include<conio. h> {
Int power (int n,int p); If(y==1)
Void main()
return(x);
{
Int x,y;
Else
Cout<<“enter any two numbers return(x*power(x,y-
(a number and its power)”; 1));
Cin>>x>>y; }
Cout<<“result =”<<power(x, y);
getch();
}
Check the above program using X=5,
#include<iostream. h> int fact (int n)
#include<conio. h> {
int fact (int n); If(n==1)
Void main() return (1);
{ Else
int a; return(n*fact(n-1));
Cout<<“enter any number”; }
Cin>>a;
Cout<<“factorial =” << fact (a);
getch();
}

You might also like