Top Banner
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
36
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Functions assignment

FUNCTIONS

SUBMITED TO:SIR ASIM

SUBMITTED BY:MUHAMMAD AWAIS FAZALAHMAD KAMALABDULLAH MUMTAZDANISH BARKAATWAJAHAT HUSSAINAHSAN UR RAHEEM

BSCS-1 (MORNING)

SECTION-A

Page 2: Functions assignment

FUNCTIONS

A function is 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.

Page 3: Functions assignment

LESS PROGRAMMING TIME:

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

Page 4: Functions assignment

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 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};

Page 5: Functions assignment

SCOPE OF A FUNCTION 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.

Page 6: Functions assignment

#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;                    }

Page 7: Functions assignment

EXPLANATION:-

The above program 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.

Page 8: Functions assignment

PROGRAMS1. User Write 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:

OUTPUT:

Please enter value of a:Please enter value of b:

Please enter value of a: 12Please enter value of b: 7

Sum: 19

#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();}

int Add(int x, int y){int z; z= x+y;return z;}

Page 9: Functions assignment

2. Take radius from 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:

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:

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:

Please enter radius of the circle:

Please enter radius of the circle: 10Area: 314

enter value of s:enter value of t:

Page 10: Functions assignment

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:

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:

enter value of s: 12enter value of t: 7

Difference: 5

Please enter the number:

Page 11: Functions assignment

PROGRAM:

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:

Please enter the number: 6720

#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(); }

int fact(int n) { int f=1,i=1; while (i<=n) { f=f*i; i=i+1; } return f; }

Enter the Celsius Temperature =

Page 12: Functions assignment

OUTPUT:

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:

PROGRAM:

#include<iostream.h>#include<conio.h>

lar (int z[],int h){

Enter Number = (This Message will displayed 5 times)

Enter Centigrade Temperature = 100Fahrenheit Temperature is = 212

#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; }

Page 13: Functions assignment

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

int M=z[0];for (int j=0;j<h;j++){if (z[j] > M){M=z[j];}}return M;}

OUTPUT:

7. Write a Program 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:

PROGRAM:

#include<iostream.h> void Result (int a,int b)

Enter Number = 45Enter Number = 50Enter Number = 774Enter Number = 1050Enter Number = 12Largest Number is = 1050

Enter Length =

Enter Width =

Page 14: Functions assignment

#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();}

{ 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

8. Write a Program 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.

Page 15: Functions assignment

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;}

OUTPUT:

Enter Hypotenuse =Enter Perpendicular =Enter Base =

Enter Hypotenuse = 5Enter Perpendicular = 4Enter Base = 3It is Right Angled TriangleEnter Hypotenuse = 3Enter Perpendicular = 2Enter Base = 1It is not Right Angled Triangle

Page 16: Functions assignment

9. Write a 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<<"\n\nArea is : "<<y; cout<<"\nPerimeter is : "<<z;}

OUTPUT:

Length =Width =

Length = 20Width = 20

Area is : 400Perimeter is : 800

Page 17: Functions assignment

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:

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:

11. Write a program 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.

Enter Side A =Enter Side B =

Enter Side A = 10Enter Side B = 10

Enter Side C = 10

Area of Triangle is : 43.30127

Page 18: Functions assignment

INPUT:

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:

12. Write a program 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().

Enter Marks of student (This will appear 5 times)

Enter Marks of Student 20Enter Marks of Student 30Enter Marks of Student 10Enter Marks of Student 50Enter Marks of Student 80

Average = 38

Page 19: Functions assignment

INPUT:

PROGRAM:

#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<<"\n\nSin("<<a<<") = "<<S; cout<<"\nCos("<<a<<") = "<<C; getch();

}

OUTPUT:

13.Write a Program 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 Value =

Enter Value = 45

Sin(45) = 0.850704

Cos(45) = 0.525322

Page 20: Functions assignment

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:

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.

INPUT:

Enter the Value of A =

Enter the Value of B=

Enter the Value of A =10Enter the Value of B=20GCD of A and B is =10

Enter the Number X =Enter the Number Y =Enter the Number Z =

Page 21: Functions assignment

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 12Enter the second number 45Enter the third umber 787larger 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 =

Page 22: Functions assignment

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:

16.Write a Program to find the lowest number in array using function?

Enter the Base =2Enter the Exponent =5Power is =32

Page 23: Functions assignment

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:

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

Enter the Number = (This message will displayed 5 times)

Page 24: Functions assignment

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:

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:

Enter Number = 12 Enter Number = 34 Enter Number = 56 Enter Number = 89 Enter Number = 45

Enter a number

3*1=33*2=63*3=93*4=123*5=153*6=183*7=213*8=24

Page 25: Functions assignment

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:

PROGRAM:

#include<iostream.h>#include<conio.h>void leap (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:

3*1=33*2=63*3=93*4=123*5=153*6=183*7=213*8=24

Enter year:

Page 26: Functions assignment

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 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++)

{

Enter year : 2012

It is leap year.

Page 27: Functions assignment

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";

}

Output:

Enter five Integers :

12

13

14

15

16

The values in array:

12 13 14 15 16

Page 28: Functions assignment

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>

#include<conio.h>

void alphabet(int);

void main()

{

clrscr();

Page 29: Functions assignment

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:

Enter any Character = a

It is vowels

Enter any Character = c

It is consonants