The document discusses functions in C++. It defines a function as a named block of code that performs some action. Functions allow code to be reused by calling the function by name. They make programs easier to modify, maintain and develop. The document describes different types of functions like user-defined and built-in functions. It also covers function declaration, definition, scope, passing parameters, and provides examples.
FUNCTIONS
SUBMITED TO:
SIR ASIM
SUBMITTED BY:
MUHAMMAD AWAIS FAZAL
AHMAD KAMAL
ABDULLAH MUMTAZ
DANISH BARKAAT
WAJAHAT HUSSAIN
AHSAN UR RAHEEM
BSCS-1 (MORNING)
SECTION-A
2.
FUNCTIONS
A functionis a named block of code that performs some action. The statement
written in a function is executed when it is called by its name. Each function has a
unique name. Functions are the building blocks of c++ programs. They encapsulate
pieces of code to perform specified operation. The functions are used to
accomplish the similar kinds of tasks again and again without writing the same
code again. They are used to perform the tasks that are repeated many times.
The control moves in the function when a function is called. All statement of the
function is executed and then the control again moves back to the point where the
function was called along with possible returned value.
The function provides a structured programming approach. It is modular way of
writing programs. 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 FUNCTION:
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 functions are not used. The piece of code that is executed repeatedly is stored in
a separate function. The real reason of using function is to divide a program into
different parts. These parts of a program can be managed easily.
ADVANTAGES OF FUNCTION:
EASIER TO MODIFY:
A length program can be divided into small function. It is easier to write small
functions instead of writing one long program. A program is written to solve a
particular problem. A programmer easier can focus attention on a specific problem.
It makes programming easier.
EASY 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.
EASY TO MAINTAIN:
Functions are easierto maintain than long programs. Each function contains
independent code. A change in the function does not affect other parts of program.
3.
LESS PROGRAMMINGTIME:
A program may consist of many functions. These functions are written as
independent programs. Different programmers can work on different at the same
time. It takes far less time to complete the program.
TYPES OF FUNCTIONS:
1. User-defined functions
2. Build-in functions
USER-DEFINED FUNCTIONS:
A type of function written by programmer is known as user-defined function.
User defined has a unique name. A program may contain user-defined functions.
BUILD-IN FUNCTIONS:
A type of function that is available as a part of language is known as build-in
function, or library function. These functions are ready-made programs. These
functions are stored in different header files. Build-in function makes programming
faster and easier. C++ language provides many build-in functions to solve different
problems. For example: clrscr(); is a build-in function to clear the screen. It is a
part of a header file called conio.h.
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.
Function name
Function return type
Number and types of parameters
SYNTAX:
The syntax of the function declaration is as follows.
Return-type Function-name (parameters);
Return-type: It indicates the type of value that will be return 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.
4.
FUNCTION-NAME: It indicatesthe 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 value that is 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.
The parameters are given in two ways:
Only 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);
FOR EXAMPLE:
int random (float);
Above example indicates that the random Function will accept one float value as a
argument and it will return the integer value.
User defined Functions are further divided into four types.
1. Functions which take arguments and return no value.
2. Functions which does not take any arguments but return a value.
3. The function which takes parameter and also returns the value.
4. The function which does not take any argument and does not return any value.
FUNCTIONS DEFINITION:
Functions definitions are the collection of statements which tells about its working
and purpose. It could be defined in three ways.
1. Before the Main() Method.
2. After the Main() Method.
3. In a Separate header files.
Function declaration is not necessary if it is defined before the Main Method.
Function declaration is essential if it is defined after the Main Function.
If Function definition is stored in a header file then it could be used anytime by
including the particular header file in a program.
SYNTAX OF A FUNCTION DEFINITION:
(Return type) (Name) (Arguments)
{
Collection of Statements about functionality
};
5.
SCOPE OF AFUNCTION IN C++:
Its scope depends upon the place where it is declared, in the terms of scope they
are divided into two types:
1. Local Functions.
2. Global Functions.
LOCAL FUNCTIONS:
They are declared into another Function. They could only be accessed inside the
Function in which they are declared. In another words Functions which are
declared inside the Main Method are called local Methods.
GLOBAL FUNCTIONS:
These are declared outside the Main Method, they could be accessed anywhere
in the program.
PASSING PARAMETERS TO A FUNCTION:
Parameters or arguments are the values which are provided to the Function when it
is called. They are given in the brackets, if there is more than one argument than
these parameters are separated by the coma. If there is no argument then the
Function is called without providing any values in the parentheses.
Arguments which are given during function call are called the Actual arguments.
Arguments which are used during Function declaration are called Formal
parameters.
There are two ways to pass the Arguments to the Functions.
1. Pass by Value.
2. Pass by Reference.
PARAMETERS PASS BY VALUE:
Parameters pass by value is a process in which values of Actual arguments are
copied to Formal parameters. In this process if the value of formal Arguments is
changed then it does not affect the values of actual Arguments. This is the most
commonly used process of passing the parameters.
Example of Parameters pass by value:
Following is the program of prime numbers which is done by the help of Methods
to which Arguments are passed by value.
6.
#include<iostream.h>
#include<conio.h>
voidfprime(int);
main()
{
inti, j;
cout<<"Enter the number: ";
cin>>j;
fprime(j);
getch();
}
voidfprime(inta)
{
intans=0;
for(inti=2; i<a; i++)
{
if(a%i==0)
{
ans=1;
}
}
if(ans==1)
{
cout<<a<<" is not a Prime Number "<<endl;
}
else
cout<<a<<" is a Prime Number "<<endl;
}
7.
EXPLANATION:-
The aboveprogram will declare the Function fprime. Then it will take the input
from the user and assign it to the variable j. Then fprimeis called and variable j is
passed as argument. Therefore copy of the Actual parameter j is created into the
Former argument a, then loop will come into action and check the condition, if
entered number modulus I is equal to zero then the entered number is not a prime
number, else entered number is a prime number.
PARAMETERS PASS BY REFERENCE:
Parameters pass by reference is a process in which actual Arguments and formal
Arguments are points towards the same memory location. In this process if the
value of formal arguments is changed then the value of actual parameters will also
be changed.
8.
PROGRAMS
1. UserWrite a program using function which accept two integers as an argument and
return its sum. Call this function from main( ) and print the results in main( ).
DESCRIPTION:
Get two numbers from user and add them using function.
METHOD:
User will enter two numbers “a” and “b” , by using function , it will return their sum to the main
and then print it.
INPUT:
PROGRAM:
#include<iostream.h>
#include<conio.h>
int Add(int ,int);
void main()
{
clrscr();
int a, b, c;
cout<<"please enter value of a:";
cin>>a;
cout<<"please enter value of b:";
cin>>b;
c=Add(a,b);
cout<<”n”<<”Sum: ”<<c;
getch();
}
OUTPUT:
int Add(int x, int y)
{
int z;
z= x+y;
return z;
}
Please enter value of a:
Please enter value of b:
Please enter value of a: 12
Please enter value of b: 7
Sum: 19
9.
2. Take radiusfrom the user and show the area of circle using function.
DESCRIPTION:
Get radius of circle from user and print area of circle using functions.
METHOD:
User will enter radius of circle, and by using function it will return area of circle to the main,
which prints the area on screen.
INPUT:
Please enter radius of the circle:
PROGRAM:
#include<iostream.h>
#include<conio.h>
double Area(int);
void main()
{
clrscr();
int a;
double R;
cout<<"Please enter radius of the circle :";
cin>>a;
R=Area(a);
cout<<”Area is: ”R;
getch();
}
double Area(int x)
{
double A;
A=(3.14)*x*x;
return A;
}
OUTPUT:
Please enter radius of the circle: 10
Area: 314
3. write a program to subtract any two numbers given by user in function.
DESCRIPTION:
Get two numbers from user and subtract them using function.
METHOD:
User will enter two numbers “a” and “b”, by using function, it will return their value after
subtracting them to the main and then print it.
INPUT:
enter value of s:
enter value of t:
10.
PROGRAM:
#include<iostream.h>
#include<conio.h>
int sub(int ,int );
void main()
{
int s,t ,u;
cout<<"enter value of s:";
cin>>s;
cout<<"enter value of t:";
cin>>b;
u=sub(s,t);
cout<<”n”<<”Difference: ”<<u;
getch();
}
int sub(int x, int y)
{
int M;
M=x-y;
return M;
}
OUTPUT:
enter value of s: 12
enter value of t: 7
Difference: 5
4. Write a function to calculate the factorial value of any integer as an argument. Call
this function from main( ) and print the results in main( ) .
DESCRIPTION:
Get a number from user, and print its factorial using functions.
METHOD:
User will enter a number and by using while loop in integer function the program will return the
factorial to the main, and then print it on screen.
INPUT:
Please enter the number:
11.
PROGRAM:
#include<iostream.h>
#include<conio.h>
int fact(int);
void main()
{
int p ,R;
cout<<"please enter the number: ";
cin>>p;
R=fact(p);
cout<<R;
getch();
}
OUTPUT:
5. Write a Program to convert the Celsius into Fahrenheit Temperature? Using
Function.
DESCRIPTION:
In this program we convert the Celsius temperature into Fahrenheit temperature in
function.
METHOD:
In this program we take an integer and double and input by user then call the function
and return the value.
INPUT:
PROGRAM:
int fact(int n)
{
int f=1,i=1;
while (i<=n)
{
f=f*i;
i=i+1;
}
return f;
}
Enter the Celsius Temperature =
#include<iostream.h>
#include<conio.h>
double result(int);
void main()
{
clrscr();
int c;
double F;
cout<<"Enter Centigrade Temprature
= ";
cin>>c;
F=result(c);
cout<<"FarehiteTemprature is = "<<F;
getch();
}
double result(int w)
{
double t;
t= w*9/5+32;
return t;
}
Please enter the number: 6
720
12.
OUTPUT:
Enter CentigradeTemperature = 100
Fahrenheit Temperature is = 212
6. Write a Program to Print out the Largest Number? Using Function.
DESCRIPTION:
In this program we find the largest number using array in function.
METHOD:
In this program we take two integers and using loop and then call the function.
INPUT:
Enter Number = (This Message will displayed 5 times)
PROGRAM:
#include<iostream.h>
#include<conio.h>
intlar(int z[],int h);
void main()
{
clrscr();
int a[5],largest=0;
for (int i=0;i<5;i++)
{
cout<<"Enter Number";
cin>>a[i];
}
largest= lar(a,5);
cout<<"Largest No is"<<largest;
getch();
}
lar (int z[],int h)
{
int M=z[0];
for (int j=0;j<h;j++)
{
if (z[j] > M)
{
M=z[j];
}
}
return M;
}
OUTPUT:
Enter Number = 45
Enter Number = 50
Enter Number = 774
Enter Number = 1050
Enter Number = 12
Largest Number is = 1050
13.
7. Write aProgram to print out that this is Square or Rectangle? Using Function.
DESCRIPTION:
In this program input the value from user in function programming and find out that it is
rectangle or a square.
METHOD:
In this program we take two integers and entered the value by user and call the function
to print the rectangle or square, in the program not return the value because it is void
function.
INPUT:
Enter Length =
Enter Width =
PROGRAM:
#include<iostream.h>
#include<conio.h>
void Result(int,int);
void main()
{
intl,w;
cout<<"Enter Length = ";
cin>>l;
cout<<"Enter Width = ";
cin>>w;
Result (l,w);
getch();
}
void Result (int a,int b)
{
if (a==b)
{
cout<<"n"<<"It is Square"<<"n";
}
else
{
cout<<"n"<<"It is Rectangle"<<"n";
}
}
OUTPUT:
Enter Length = 10
Enter Width = 10
It is Square
Enter Length = 15
Enter Width = 30
It is Rectangle
14.
8. Write aProgram and input by user to print out that is correct Right Angled
Triangle or not Right Angled Triangle? Using Function
DESCRIPTION:
In this program call the function and entered the value by user and print out that is
correct right angled triangle or not.
METHOD:
In this program we take three integer and input the value by user and then call the
function, in the function we also take four integers and first three integers multiply it
and return the value.
INPUT:
PROGRAM:
#include<iostream.h>
#include<conio.h>
int check (int,int,int);
void main()
{
clrscr();
int H,P,B,T;
cout<<"Enter Hypotenuse";
cin>>H;
cout<<"Enter Perpendicular";
cin>>P;
cout<<"Enter Base";
cin>>B;
T=check (H,P,B);
if (T==1)
{
cout<<"It is Right Triangle";
}
else
{
cout<<"It is not Right Triangle";
}
getch();
}
int check (int x,inty,int z)
{
int R;
if (x*x == y*y + z*z)
{
R=1;
}
else
{
R=2;
}
return R;
}
Enter Hypotenuse =
Enter Perpendicular =
Enter Base =
15.
OUTPUT:
9. Writea Program and input length and width of rectangle by user to print out the
area and perimeter of rectangle? Using Function.
DESCRIPTION:
User will enter length and width of the rectangle and program will find the
area and perimeter of that rectangle.
METHOD:
In this program, two value are entered by user i-e.; length and width. The
function will not return any value (such function is called void function) but
it will print the area and perimeter from the function.
INPUT:
PROGRAM:
#include<iostream.h>
#include<conio.h>
void Rect (int,int);
void main()
{
clrscr();
int L,W,A,P;
cout<<"Length = ";
cin>>L;
cout<<"Windth = ";
cin>>W;
Rect(L,W);
getch();
}
void Rect(int a, int b)
{
int z,
y=a*b;
z=2*(a*b);
cout<<"nnArea is : "<<y;
cout<<"nPerimeter is : "<<z;
}
Enter Hypotenuse = 5
Enter Perpendicular = 4
Enter Base = 3
It is Right Angled Triangle
Enter Hypotenuse = 3
Enter Perpendicular = 2
Enter Base = 1
It is not Right Angled Triangle
Length =
Width =
16.
OUTPUT:
Length =20
Width = 20
Area is : 400
Perimeter is : 800
10. Write a Program and input three sides of triangle by user to print out the area of
triangle? Using Function.
DESCRIPTION:
User will enter three sides of triangle and program will find the area of that
triangle using heroes formula.
METHOD:
In this program, three sides of triangle are entered by user, it will print the
area using library function of square root i-e.; sqrt().
INPUT:
Enter Side A =
Enter Side B =
Enter Side C =
PROGRAM:
#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
int s,a,b,c;
float x,A;
cout<<"Enter side A ";
cin>>a;
cout<<"Enter side B ";
cin>>b;
cout<<"Enter side C ";
cin>>c;
s=(a+b+c)/2;
x=s*(s-a)*(s-b)*(s-c);
A=sqrt(x);
cout<<"nArea of triangle is:" <<A;
getch();
}
OUTPUT:
Enter Side A = 10
Enter Side B = 10
Enter Side C = 10
Area of Triangle is : 43.30127
17.
11. Write aprogram to print the average marks of five students , marks are input by
user? Using array in function.
DESCRIPTION:
Take marks of five students of a class by user and print average using array in function.
METHOD:
In this program, an integer array of length 5 is taken, and marks of 5 students are entered by
user. By using function of type “double” these marks are added with each other and divided by
the total number of students i-e.; 5.
INPUT:
Enter Marks of student (This will appear 5 times)
PROGRAM:
#include<iostream.h>
#include<conio.h>
double Average(int a[]);
void main()
{
clrscr();
int M[5],s,i,Avrg;
for (s=0; s<=4; s++)
{
cout<<"Enter Marks of student ";
cin>>M[s];
}
Avrg=Average(M);
cout<<"n nAverage = "<<Avrg;
getch();
}
double Average(int a[])
{
int k=0,Z,i;
for (i=0; i<5; i++)
{
k=k+a[i];
}
Z=k/5;
return Z;
}
OUTPUT:
Enter Marks of Student 20
Enter Marks of Student 30
Enter Marks of Student 10
Enter Marks of Student 50
Enter Marks of Student 80
Average = 38
18.
12. Write aprogram to print sin() and cos() of the value entered by user. Use function
to print.
DESCRIPTION:
A value is entered by user the program will find the values of sin() and cos() of that value using
function.
METHOD:
An integer is input by user, and by using library function this program will print the values of
sin() and cos().
INPUT:
Enter Value =
PROGRAM:
Enter Side B =
Enter Side C =
#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
int a;
float S,C;
cout<<"Enter value : ";
cin>>a;
S=sin(a);
C=cos(a);
cout<<"nnSin("<<a<<") = "<<S;
cout<<"nCos("<<a<<") = "<<C;
getch();
}
OUTPUT:
Enter Value = 45
Sin(45) = 0.850704
Cos(45) = 0.525322
19.
13. Write aProgram to find the Greatest Common Divisor (GCD) using
function?
DESCRIPTION:
In this program we use function to print out the GCD of two numbers.
METHOD:
In this program we take two integers for “enter the numbers” and third integers for result
and then call the function, apply modulus and return the value.
INPUT:
Enter the Value of A =
Enter the Value of B=
PROGRAM:
#include<iostream.h>
#include<conio.h>
intgcd (int, int);
void main()
{
clrscr();
inta,b,k;
cout<<”Enter the Value of A =”;
cin>>a;
cout<<”Enter the Value of B =”;
cin>>b;
k=gcd(a,b);
cout<<GCD of A and B is =”<<k;
getch();
}
intgcd(int x,int y)
{
int g;
for(int i=1;i<=x;i++)
{
if((x%i==0) && (y%i==0) )
{
g=i;
}
}
return g;
}
OUTPUT:
Enter the Value of A =10
Enter the Value of B=20
GCD of A and B is =10
14. Write a Program to find the largest number using function?
DESCRIPTION:
In this program to find the largest number using the function.
METHOD:
In this program we enter three numbers and using function to find that which number are
largest.
20.
INPUT:
Enter theNumber X =
Enter the Number Y =
Enter the Number Z =
PROGRAM:
#include<iostream.h>
#include<conio.h>
void large (int,int, int);
void main()
{
clrscr();
int a,b,c;
cout<<"enter the first number ";
cin>>a;
cout<<"enter the second number ";
cin>>b;
cout<<"enter the third number ";
cin>>c;
large (a,b,c);
getch();
}
void large (int x,int y,int z)
{
if( (x>y) && (x>z) )
{
cout<<"large number is "<<x;
}
else if((y>x) && (y>z))
{
cout<<"large number is "<<y;
}
else
{
cout<<"large number is "<<z;
}
}
OUTPUT:
Enter the first number 12
Enter the second number 45
Enter the third umber 787
larger number is 787
15. Write a Program to find the power of any number using function?
DESCRIPTION:
In this program we find the power of number entered by using function.
METHOD:
In this program we take three integers first for enter base, second for enter exponent, and
third for result. and then for output call the function and return the value.
INPUT:
Enter the Base =
Enter the Exponent =
21.
PROGRAM:
#include<iostream.h>
#include<conio.h>
intpwr (int, int);
void main()
{
clrscr();
inta,b,k;
cout<<"Enter the Base =";
cin>>a;
cout<<"Enter the Exponent =";
cin>>b;
k=pwr (a,b);
cout<<"Power is ="<<k;
getch();
}
int pwr (int x,int y)
{
int g=1;
for(int i=1;i<=y;i++)
{
g=g*x;
}
return g;
}
OUTPUT:
Enter the Base =2
Enter the Exponent =5
Power is =32
16. Write a Program to find the lowest number in array using function?
DESCRIPTION:
In this program to print out the lowest number using array in function.
METHOD:
In this program we take an integer and array and using loop to print & then call the
function.
INPUT:
Enter the Number = (This message will displayed 5 times)
22.
PROGRAM:
#include<iostream.h>
#include<conio.h>
int l(int z[],int h);
void main()
{
clrscr();
int a[5],lowest=a[0];
for (int i=0;i<5;i++)
{
cout<<"Enter Number = ";
cin>>a[i];
}
lowest= l(a,5);
cout<<"Lowest No is = "<<lowest;
getch();
}
int l (int z[],int h)
{
int M=z[0];
for (int j=0;j<h;j++)
{
if (z[j] < M)
{
M=z[j];
}
}
return M;
}
OUTPUT:
Enter Number = 12
Enter Number = 34
Enter Number = 56
Enter Number = 89
Enter Number = 45
Lowest No is = 12
17. write a program that input a number in main function and passes the
number to function.The function display table of that number.
DESCRIPTION:
Get an integer from user, and print its table using function.
METHOD:
User will enter some number and by using loop in function it will print table of that
number without returning any value to the main().
INPUT:
Enter a number
23.
PROGRAM:
#include<iostream.h>
#include<conio.h>
void table(int);
void main()
{
int num;
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;
}
}
OUTPUT:
3*1=3
3*2=6
3*3=9
3*4=12
3*5=15
3*6=18
3*7=21
3*8=24
3*9=27
3*10=30
18. Write a program to find whether the year is leap or not?
DESCRIPTION:
Get a year number from user and print year is leap or not.
METHOD:
User will enter year no. and by using void function it will print the year is leap or notwith
returning any value.
INPUT:
Enter year:
PROGRAM:
24.
#include<iostream.h>
#include<conio.h>
voidleap (int);
void main()
{
clrscr();
int y;
cout<<”Enter year :”;
cin>>y;
leap(y);
getch();
}
Void leap(int x);
{
if (x%4==0)
{
cout<<”nIt is a leap year”;
}
else
{
cout<<”nIt is not leap year”;
}
}
OUTPUT:
19 Write a program that display a square of character usi//write a program that
inputs five integers in an array and passes the array to a function.
Description:
In this program we take an integers and display in arrays.
Method:
In this program we entered 5 integers and then call the function, using loop and
display the integers as in array.
Input:
Enter year : 2012
It is leap year.
Enter year : 2014
It is not leap year.
25.
Enter five Integers:
#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";
26.
}
Output:
Enterfive Integers :
12
13
14
15
16
The values in array:
12 13 14 15 16
20 Write a program to printout that which is a vowels and consonants? Using
function.
Description:
In this program to find we use function and decide that which are vowels and
consonants.
Method:
In this program we take a single character to input the any characters and then take
result in the function.
Input:
Enter any Character =
Program:
#include<iostream.h>
27.
#include<conio.h>
void alphabet(int);
void main()
{
clrscr();
char b;
cout<<"Enter any Character = ";
cin>>b;
alphabet(b);
getch();
}
void alphabet(int t)
{
if ((t=='a') || (t=='e') || (t=='i') || (t=='o') || (t=='u'))
{
cout<<"It is vowels";
}
else
{
cout<<"It is consonants";
}
Output:
28.
Enter any Character= a
It is vowels
Enter any Character = c
It is consonants