New Fakhre Alam Lect 9 (Lab & Theory)
New Fakhre Alam Lect 9 (Lab & Theory)
New Fakhre Alam Lect 9 (Lab & Theory)
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.
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
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.
Syntax:
Return-type Function-name (parameters) Function header
{
statement 1;
statement 2;
….. Function body
statement N;
}
Functions
Function Call:
When the control returns back to the calling function, the remaining statements in the
calling function are executed.
Functions
Function Call:
Called 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.
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";
}
#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
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.
#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.)
#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.
#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
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.
#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 name of the array refers to the memory address of its first element.
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.
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.
#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;
} }
}