Function
A function is a named unit of a group of program statements, which can be invoked or called from another part of program as per requirement.
It is a subpart of a program which can be reused when
required.
It is generally used to make the program easy to
understand and to reduce the mess at one place.
Function generally have 3 parts –
Function declaration, Function definition, Function
calling.
Syntax :
Function_Data_type function_name (argument1, argument2 )
{
Function body ;
}
Function declaration
It is used to let the compiler know that there is some function exist in the program.
Function definition
It is used to define the
body of the function or content of the function.
Function calling
It is used to call the
function when there is a requirement.
Program to sum two number entered by user using
function.
Method -1 :
#include<iostream.h>
#include<conio.h>
/* Now defining the
function */
void summer ( int numb1, int numb2 ){
int sum;
sum = numb1 + numb2 ;
cout<<”\n The summation is
= ”<<sum ;
}
/* Here, the function datatype is void and function name is
summer. */
void main()
{
clrscr();
int a , b ;
cout<<”\n Enter a number = ” ;
cin>>a;
cout<<”\n Enter another number = ” ;
cin>>b;
summer (a, b) ;
/* This is Function calling */
getch();
}
Method -2 :
#include<iostream.h>
#include<conio.h>
/* Now defining the
function */
int summer ( int numb1 , int numb2 ){
int sum;
sum = numb1 + numb2 ;
return sum ;
}
/* Here, the function datatype is int and function name is
summer. */
/* Since, the datatype is int so, it return a integer value.
That’s why , it have a return term.*/
void main()
{
clrscr();
int a , b, result;
cout<<”\n Enter a number = ” ;
cin>>a;
cout<<”\n Enter another number = ” ;
cin>>b;
result = summer (a, b) ;
/* Function calling and storing the returned value at result.*/
cout<<”\n The output is = ”<<result ;
getch();
}
Method -3 :
#include<iostream.h>
#include<conio.h>
/* Now defining the function */
void summer ( ){
int a , b, sum ;
cout<<”\n Enter a number = ” ;
cin>>a;
cout<<”\n Enter another number = ” ;
cin>>b;
sum = numb1 + numb2 ;
cout<<"\n The result is = "<<sum ;
}
void main()
{
clrscr();
summer ( ) ;
getch();
}
0 comments:
Post a Comment
Please give your valuable suggestions