Sunteți pe pagina 1din 50

Functions

Dr. Fakhre Alam Khan


MED UET Peshawar
Functions
 A function is a named block of code that performs some action.
 The statements written in a function are executed when it is called by its name.
 The functions provide a structured programming approach.
 The whole program logic is divided into a number of smaller modules or functions.
 The main function calls these functions when they are needed to execute.

Importance of Functions:
 A program may need to repeat the same piece of code at various places.
 It may be required to perform certain tasks repeatedly.
 The program may become very large if function are not used.
 The piece of code that is executed repeatedly is stored in a separate function.
 The real reason of using functions is to divide a program into different parts.
 These parts of a program can be managed easily.
Functions
Advantages of Functions:
1) Easier to Code:
 A lengthy program can be divided into small functions.
 It is easier to write small functions instead of writing one long program.
 A function is written to solve a particular problem.
 A programmer can focus attention on a specific problem. It makes programming easier.

2) Easier to Maintain:
 Functions are easier to maintain than long programs.
 Each function contains independent code.
 A change in the function does not affect other parts of program.
Functions
3) Easier to Modify:
 Each function has a unique name and is written as an independent block.
 If there is any error in the program, the change is made to particular function in which
error exists.
 A small function is easier to modify than a large program.

4) Reusability:
 The code written in functions can be reused as and when required.
 A function but can be executed many times.
 A function is written to so1ve a particular problem. Whenever that problem has lo be
solved, the function can be executed.

5) Less Programming Time:


 A program may consist of many functions.
 These functions are written as independent programs.
 Different programmers can work on different functions al the same time.
 It takes far less time to complete the program.
Functions
Types of Functions in C++

1) User-defined Functions:
 A type of function written by programmer is known as user-defined function.
 User-defined function has a unique name.
 A program may contain many user-defined functions.

2) Built-in Functions:
 A type of function that is available as a part of language is known as built-in function or
library function.
 These functions are ready-made programs.
 These functions are stored in different header files.
 Built-in functions make programming faster and easier.
 C++ language provides many built-in functions to solve different problems.
 For example, clrscr is a built-in function to clear the screen. It is part of a header file
called conio.h
Functions
User-defined Functions:
 A user-defined function consists of the following:
a) Function declaration
b) Function definition

a) Function declaration or function prototype:


 Function declaration is a model of a function. It is also called function prototype.
 It provides information to compiler about the structure of the function to be used in
program.
 It ends with a semicolon.
 Function prototypes are usually placed at the beginning of the source file just before the
main() function.
 Function declaration consists of the following parts:
Functions
a) Function declaration or function prototype:
Function declaration consists of the following parts:
• Function name
• Function return type
• Number and types of parameters
Syntax
Return-type Function-name (parameters);
Return-type It indicates the type of value that will be returned by function. For example, int is used
as return type if the function returns integer value. If the function returns no value, the
keyword void is used.
Function-name It indicates the name of function. The rules for specifying a function name is similar to
the rules for declaring a variable. Each function should have a unique name.
Parameters Parameters are the values that are provided to a function when the function is called.
Parameters are given in parentheses. If there are many parameters, these are separated by
commas. If there is no parameter, empty parentheses are used or keyword void is written
in the parentheses.
Functions
a) Function declaration or function prototype:
The parameters are given in two ways:
• Only data types of the parameters, are written in prototype as follows:
int add(int, int);
• Both data types and names of parameters are written in prototype as follows:
int add(int a, int b );

Examples:
void show(void);
void line(char);
int cube(int);
long factorial(int n);
int add(int a, int b, int c);
Functions
b) Function Definition:

 A set of statements that explains what a function does is called function definition.
 The function definition can be written at the following places:
1. Before main() function
2. After main() function
3. In a separate file.

 Function declaration is not required if the function definition is written before main()
function.
 Function declaration is compulsory if function definition is written after main() function.
 If function definition is written in a separate file then it can be used by including that file
in the program using #include preprocessor directive.
Functions
b) Function Definition:
 The function definition consists of two parts:

i) Function Header:
 The first line of function definition is known as function header.
 It is also called function declarator.
 It is similar to function prototype.
 The only difference is that it is not terminated with semicolon.
 The number of parameters and sequence parameters in function header and function
prototype must be same.

ii) Function Body:


 The set of statements which are executed inside the function is known as function body.
 The body of function appears after function declarator and the statements are written in
curly braces { }.
Functions
b) Function Definition:

Syntax:
Return-type Function-name (parameters) Function header
{
statement 1;
statement 2;
….. Function body

statement N;
}
Functions
Function Call:

 The statement that activates a function is known as function call.


 A function is called with its name.
 Function name is followed by necessary parameters in parentheses.
 If there are many parameters, these are separated by commas.
 If there is no parameter, empty parentheses are used.
 The following steps take place when a function is called:

1. The control moves to the function that is called.


2. All statements in the function body arc executed.
3. The control returns back to the calling function.

 When the control returns back to the calling function, the remaining statements in the
calling function are executed.
Functions
Function Call:
Called function

Calling function void Fun( )


{
..........
executed.
void main( ) ..........
{ ..........
.......... }
Fun();
Function calls ..........
..........
Fun(); executed.
..........
..........
}
Write a program that displays a message "Programming makes life interesting" on screen using function.

#include <iostream.h>
#include <conio.h>
void show(void);
void main()
{
clrscr();
show();
getch();
}
void show()
{
cout<<"Programming makes life interesting.";
}
Functions
Scope of Functions:
 The area in which a function can be accessed is known as the scope of a function.
 The scope of any function is determined by the place of function declaration.
 Different types of functions on the basis of scope are as follows:

1. Local Functions:
 A type of function that is declared within another function is called local function.
 A local function can be called within the function in which it is declared.

Example:
void main()
{
clrscr();
show();
getch();
}
Functions
2. Global Functions:
 A type of function that is declared outside any function is called global function.
 A global function can be called from any part of the program.

Passing Parameters to Functions:


 Parameters are the values that are provided to a function when the function is called.
 Parameters are given in the parentheses. If there are many parameters, these are separated
by commas.
 If there is no parameter, empty parentheses are used. Both variables and constants can be
passed to a function as parameters.
 The sequence and types of parameters in function call must be similar to the sequence
and types of parameters in function declaration.
a) Parameters in function call are called actual parameters.
b) Parameters in function declaration are called formal parameters.
 When a function call is executed, the values of actual parameters are copied to formal
parameters.
Pass by Value:
Functions
 A parameter passing mechanism in which the value of actual parameter is copied to
formal parameters of called function is known as pass by value.
 If the function makes any change in formal parameter, it does not affect the values of
actual parameter.
 It is the default mechanism for passing parameters to functions.
Formal Parameter num
void show(int num)
Function declaration void show(int); Function definition
{
void main() cout<<"The number is: "<<num;
( }
int n;
cout<<"Enter number: ";
cin>>n;
Function call show(n); Actual Parameter n
cout<<"End of Program" ;
}
Variable num

Variable n
Write a program that inputs two numbers in main() function, passes these numbers to a function. The function
displays the maximum number.

#include <iostream.h>
#include <conio.h>
void max(int a, int b);
void main()
{
clrscr();
int x, y;
cout<<"Enterr two numbers: ";
cin>>x>>y;
max(x,y);
getch();
}
void max(int a , int b)
{
if(a > b)
cout<<"Maximum number is "<<a;
else
cout<<"Maximum number is "<<b;
}
Write a program that inputs a number in main function and passes the number to a function. The function
displays table of that number.

#include <iostream.h>
#include <conio.h>
void table(int n);
void main()
{
int num;
clrscr();
cout<<"Enter a number: ";
cin>>num;
table(num);
getch();
}
void table(int n)
{
int c;
for(c=1; c<=10; c++)
{
cout<<n<<" * "<<c<<" = "<<n*c<<endl;
}
}
Pass by Reference: Functions
 A parameter passing mechanism in which the address of actual parameter is passed to the called
function is known as pass by reference.
 The formal parameter is not created separately in the memory.
 formal parameter becomes a second name of actual parameter.
 It means that single memory location is shared between actual parameter and formal parameter.
 If the called function makes any change in formal parameter, the change is also available in
calling function. Formal Parameter num
void show(int num)
Function declaration void show(int); Function definition
{
void main() cout<<"The number is: "<<num;
( }
int n;
cout<<"Enter number: ";
cin>>n;
Function call show(n); Actual Parameter n
cout<<"End of Program";
}

Shared memory location


Write a program that inputs two integers in main() function and passes the integers to a function by reference. The
function swaps the values. The main() function should display the value before and after swapping.

#include <iostream.h>
#include <conio.h>
void swap(int &x, int &y);
void main()
{ swap(a, b);
clrscr(); cout<<"Values after swapping :\n";
int a, b; cout<<"a = "<<a<<endl;
cout<<"Enter an integer: "; cout<<"b = "<<b<<endl;
cin>>a; getch();
cout<<"Enter an in teger: "; }
cin>> b; void swap(int &x, int &y)
cout<<"Values before swapping:\n"; {
cout<<"a = ''<<a<<endl ; int t;
cout<<"b = "<<b<<endl; t = x;
cout<<"Swapping the values... "<<endl; x = y;
y = t;
}
Difference b/w Call by Value and Call by Reference

Call by Value Call by Reference


1. Call by value passes the value of actual parameter to 1. Call by reference passes the address of actual
formal parameter. parameter to formal paramter.
2. The actual and formal parameters refer to different 2. The actual and formal parameters refer to the same
memory locations memory location.
3. Any change made by function in formal parameter 3. Any change made by function in formal parameter
does not affect the value of independently in a actually changes the value of actual parameter.
program.
4. It requires more memory. 4. It requires less memory.

5. It is less efficient. 5. It is more efficient.


Functions
Returning Value from Function:
 A function can return a single value. The return type in function declaration indicates the type of
value returned by a function. For example, int is used as return type if the function returns
integer value.
 If the function returns no value, the keyword void is used as return type.
 The keyword return is used to return the value back to the calling function.
 When the return statement is executed in a function, the controls moves back to the calling
function along with the returned value.

Formal Parameter num


int cube(int num)
Function declaration int cube(int); Function definition
{
void main() return num*num*num;
( }
int n,c;
cout<<"Enter number: ";
cin>>n;
Function call c=cube(n); Actual Parameter n
cout<<“Cube is“<<c;
}
Functions
Returning Value from Function:
Syntax
return expression;
 The calling function can use the returned value in the following ways:
1. Assignment statement 2. Arithmetic expression 3. Output statement

1. Assignment Statement
The calling function can store the returned value in a variable and then use this variable in the
program.
Formal Parameter num
int cube(int num)
Function declaration int cube(int); Function definition
{
void main() return num*num*num;
( }
int n,c;
cout<<"Enter number: ";
cin>>n;
Function call c=cube(n); Actual Parameter n
cout<<“Cube is“<<c;
}
Write a program that inputs marks in main function and passes these marks to a function. The function finds grade
of student on the basis of the following criteria: Grade A - 80 or above marks
The function returns grade back lo main function where it is displayed on the screen. Grade B - 60 to 79 marks
Grade C - 40 to 59 marks
Grade F - below 40 marks
#include <iostream.h>
#include <conio.h>
char grade(int m); char grade(int m)
void main() {
{ if(m > 80)
clrscr(); return 'A';
int marks; else if(m > 60)
char g; return 'B';
cout<<"Enter marks: "; else if(m > 40)
cin>>marks; return 'C';
g = grade(marks); else
cout<<"Your grade is "<<g; return 'F';
getch(); }
}
Functions
Returning Value from Function:
2. Arithmetic Expression
The calling function can use the returned value directly in an arithmetic expression.

Formal Parameter num


int cube(int num)
Function declaration int cube(int); Function definition
{
void main() return num*num*num;
( }
int n,c;
cout<<"Enter number: ";
cin>>n;
Function call c=5*cube(n); Actual Parameter n
cout<<“Cube is“<<c;
}
Write a program that inputs two integers. It passes first integer to a function that calculates and returns its square.
It passes second integer to another function that calculates and returns its cube. The main() functions adds both
returned values and displays the result.

#include <iostream.h>
#include <conio.h>
int sqr(int n); int sqr(int n)
int cube(int n); {
void main() return n* n ;
{ }
clrscr(); int cube(int n)
int a , b, r; {
cout<<"Enter an integer: "; return n*n*n;
cin>>a; }
cout<<"Enter an integer: " ,
cin>>b;
r = sqr(a) + cube(b);
cout<<"Result = "<<r<<endl;
getch();
}
Functions
Returning Value from Function:
3. Output Statement
The calling function can use the returned value directly in an output statement.
Formal Parameter num
int cube(int num)
Function declaration int cube(int); Function definition
{
void main() return num*num*num;
( }
int n,c;
cout<<"Enter number: ";
cin>>n;
cout<<“Cube is“<<cube(n); Actual Parameter n
}

Function call
Write a program that inputs two integers in main() function and passes the values to a function. The function finds
and returns the greatest common divisor. The main() function then displays the returned value.

#include <iostream.h>
#include <conio.h>
int gcd(int x, int y); int gcd(int x, int y)
void main() {
{ int g, i, n;
clrscr(); if(x < y)
int a , b; n = x;
cout<<"Enter an integer: "; else
cin>>a; n = y;
cout<<"Enter an integer: "; for(i=1; i<=n; i++)
cin>>b; if(x%i==0 && y%i==0)
cout<<"Greatest common divisor is "<<gcd(a, b)<<endl; g = i;
getch(); return g;
} }
Local Variable: Functions
 A variable declared inside a function is known as local variable.
 Local variables are also called automatic variables.

Syntax
auto data_type identifier; (The user of keyword auto is optional.)

Scope of Local Variable


 The area where a variable can be accessed is known as scope of variable.
 Local variable can be used only in the function in which it is declared.

Lifetime of Local Variable


 The time period for which a variable exists in the memory is known as the lifetime of variable.
 The lifetime of local variable starts when the control enters the function in which it is declared.
 Local variable is automatically destroyed when the control exits from the function and its lifetime
ends.
 When the lifetime of a local variable ends, the value stored in this variable also becomes
inaccessible.
Example

#include <iostream.h>
#include <conio.h>
void fun();
void main()
{
clrscr();
int i;
for(i=1; i<=5; i++)
fun();
getch();
}
void fun()
{
int n = 0;
n++;
cout<<"The value of n = "<<n<<endl;
}
Global Variable: Functions
 A variable declared outside any function is known as global variable.
 Global variables can be used by all functions in the program.

Scope of Local Variable


 Global variable can be used by all functions in the program.
 It means that these variables are globally accessed from any part of the program.
 Normally, global variables are declared before main function.

Lifetime of Local Variable


 Global variables exist in the memory as long as the program is running.
 These variables are destroyed from the memory when the program terminates.
 These variables occupy memory longer than local variables.
 So, global variables should be used only when these are very necessary.
Write a program that inputs a number in a global variable. The program calls a function that multiplies the value of
global variable by 2. The main function then displays the value of global variable.

#include <iostream.h>
#include <conio.h>
int g;
void fun();
void main()
{
clrscr();
cout<<"Enter a number: ";
cin>>g;
cout<<"Value of g before function call: "<<g<<endl;
fun();
cout<<"Value of g after function call: "<<g<<endl;
getch();
}
void fun()
{
g = g * 2;
}
Difference b/w Local and Global Variable

Local Variable Global Variable


1. Local variables are declared within a function. 1. Global variables are declared outside any function.

2. Local variables can be used only in functions in which 2. Global variables can be used in all functions.
they are declared.
3. Local variables are created when the control enters the 3. Global variables are created when the program starts
function in which they are declared. execution.
4. Local variables are destroyed when the control leaves 4. Global variables are destroyed when the program
the function. terminates.
5. Local variables are used when the values are to be 5. Global variables are used when values are to be shared
used within a function. among different functions.
Static Variable: Functions
 A local variable declared with keyword static is called static variable.
 The keyword static is used to increase the life time of local variable.

Scope of Static Variable


 The scope of static variable is similar to the scope of local variable.
 Static variable can be used only in the function in which it is declared.

Lifetime of Static Variable


 The lifetime of static is similar to global variable.
 Static variables exist in the memory as long as the program is running.
 These variables are destroyed from the memory when the program terminates.
 Static variables are created in the memory when the function is called for the first time.
 When the control exits from the function, these variables are not destroyed unlike local variables.
 A function that contains static variables runs faster than the function with local variables.
 This is because local variables are created each time the function is called but static variables are
created only once.
Write a program that calls a function for five times using loop. The function uses a static variable initialized to 0.
Each time the function is called, the value of static variable is incremented by 1 and is displayed on the screen.

#include <iostream.h>
#include <conio.h>
void fun();
void main()
{
clrscr();
int i;
clrscr();
for(i=1; i<=5; i++)
fun();
getch();
}
void fun()
{
static int n = 0;
n++;
cout<<"Value of n = "<<n<<endl;
}
Functions
Register Variable:
 A variable declared with register keyword is known as register variable.
 The value of register variable is stored in registers instead of RAM.
 Registers are faster than RAM so the values stored in register can be accessed faster than the
values stored in RAM.

Syntax
register data-type variable-name;

Example
register int n
Functions
Functions and Arrays:
 An array can be passed to a function as parameter.
 When an array is passed as parameter to a function, only the address of first element of the array
is passed.
 An array is passed by reference not by value.
 A separate copy of the array is not created in the function.

Syntax
Return-type Function-name (parameter[]);

Example
void display(int []);

 The above example declares a function display that will accept an array of integers as parameter.
Functions
Calling a Function with Array Parameter:
 A function with array parameter is called by giving the name of the array as actual parameter.

 The index of the array is not used in function call.

 The name of the array refers to the memory address of its first element.

 The memory address is passed to the function.

 The function then accesses the array by using the memory address.
Write a program that inputs five integers in an array and passes the array to a function. The function displays the
values of the array.

#include <iostream.h>
#include <conio.h>
void show(int arr[]);
void main()
{
clrscr();
int num[5], i;
cout<<"Enter five integers: "<<endl;
for(i=0 ; i<5; i++ )
cin>>num[i];
show(num);
getch();
}
void show(int arr[])
{
int j;
cout<<"The values in array:\n" ;
for(j=0; j<5; j++)
cout<<arr[j]<<"\t";
}
Functions
Passing Individual Array Element to Function:
 An individual element of array can also be passed to function.

 The data type of array and the data type of function parameter must be same.

 The individual element is passed to a function like a simple variable.

 Suppose a function is defined to accept an integer parameter.

 It can accept an individual element of an integer array in same way as it can accept a simple
integer variable.
Write a program that inputs five integers in an array. It passes all elements of the array to a function one by one.
The function displays the actual value of the element and its square.

#include <iostream.h>
#include <conio.h>
void square(int n);
void main()
{
clrscr();
int num[5], i;
cout<<"Enter five integers: "<<endl;
for(i=0; i<5; i++)
cin>>num[i];
cout<<"Calling the function ... "<<endl;
for(i=0; i<5; i++)
square(num[i]);
getch();
}
void square(int n)
{
cout<<n<<"\t"<<n*n<<endl;
}
Functions
Passing 2-Dimensional Array to Function:
 Two dimensional array can be passed to a function in same way as one-dimensional array.
 The two-dimensional array is also passed to a function by reference.
 The specification of first dimension is not necessary.
 However, the second dimension is always required.

Examples:
void fun (int n[] []); // Error. The second dimension is required.
void square(int n [] [3]) // OK.
void square(int n[3][2]) // OK.
Write a program that inputs. values in a two-dimensional array with three rows and two columns. The program
passes the array to a function. The function returns the maximum value in the array.

#include <iostream.h>
#include <conio.h>
int max(int arr[3][2]);
void main()
{ int max(int arr[3][2])
clrscr(); {
int num[3][2], i, j, mx; int r, c, m;
for(i=0; i<3; i++) m = arr[0][0];
for(j=0; j<2; j++) for(r=0; r<3; r++)
{ for(c=0; c<2; c++)
cout<<"Enter value for num["<<i<<"]["<<j<<"]: "; if(arr[r][c] > m)
cin>>num[i][j]; m = arr[r][c];
} return m;
mx = max(num); }
cout<<"The maximum value is "<<mx<<endl;
getch();
}
Assignment # 3
Write down pseudo code (algorithm) and make flow chart of the
given problems.

Write down code of all programs as well…

Next week: Quiz 3 (be ready…)


Write a program that inputs a number and displays its precessor and successor numbers using function.

#include <iostream.h>
#include <conio.h>
void value(int);
void main()
{
clrscr();
int x;
cout << "Enter an integer : ";
cin>>x;
value(x);
getch();
}
void value(int x)
{
int p, n;
p=x-1;
n=x+1;
cout <<"The number before "<<x<< " is " <<p<<endl;
cout <<"The number after "<<x<< " is " <<n<<endl;
}
Write a program that inputs a number in main function and passes the number to a function. The function displays
the factorial of that number.

#include <iostream.h>
#include <conio.h>
void factorial(int n);
void main()
{
int num;
clrscr();
cout<<"Enter a number: ";
cin>>num;
factorial(num);
getch();
}
void factorial(int n)
{
int i;
long fact;
fact= 1;
for(i=1; i<=n; i++)
fact *= l;
cout<<"Factorial of "<<n<<" is "<<fact;
}
Write a program to check whether a number is prime number, even number or odd number using function.

#include<iostream.h>
#include<conio.h>
void chk_number(int n) void main()
{ {
int c=0, i; int n;
for(i=2; i<n; i++) cout<<"\nEnter a number: ";
{ cin>>n;
if(n%i==0) cout<<''\nNature of number \n";
c=1; cout<<"\n----------------------- \n";
} chk_number(n);
if(n%2==0 && c==0) getch();
cout<<n<<" is a prime even number: "; }
else if(n%2!==0 && c==0)
cout<<n<<" is a odd prime number.";
else if(n%2==0 && c!=0)
cout<<n<<" is only an even number, not prime.";
else if(n%2!=0)
cout<<n<<" is only an odd number, not prime.";
else
cout<<n<<" is not a prime number.";
}
Write a program that inputs two numbers and one arithmetic operator in main function and passes them to a
function. The function applies arithmetic operation on two numbers on the basis of the operator entered by user
using switch statement.

#include <iostream.h>
#include <conio.h> case'-':
void cal(int a, int b, char op); cout<<a<<" - "<<b<<'' = "<<a-b;
void main() break;
{ case'*':
int x, y; cout<<a<<" * "<<b<<" = "<<a*b;
char c; break;
cout<<"Enter first number, operator and second number: "; case'/':
cin>>x>>c>>y; cout<<a<<" / "<<b<<" = "<<a/b;
cal(x, y, c); break;
getch(); case'%':
} cout<<a<<" % "<<b<<" = "<<a%b;
void cal(int a, int b, char op) break;
{ default:
switch(op) cout<<"lnvalid operator!";
{ }
case'+': }
cout<<a<<" + "<<b<<" = "<<a+b;
break;
Write a program that displays a square of characters using function. The program inputs a number and a character
in main function and passes them to function. For example, if the user enters 3 and @, the function displays the
following 3 rows of the symbol @.

#include <iostream.h>
#include <conio.h>
void shape (int , char );
void main()
{
int num; void shape (int n, char c)
char ch ; {
cout << "\nEnter a number:"; int i, j;
cin >> num; for (i =1 ; i <= n ; i++)
cout << "Enter a charcter:"; {
cin >> ch; cout << endl;
shape (num, ch); for (j=1; j <= n ; j++)
getch(); cout <<c;
} }
}

S-ar putea să vă placă și