Functions In C++
Because there are no library functions with predetermined definitions, a user-defined function is one that is written by the user when writing any application. To fulfill the user's individual needs, the user must create his or her own functions. Such functions must be appropriately defined by the user. There is no such necessity to include any specific library in the program.
Different Types of User-Defined Functions in C
- Function with no arguments and no return value
- Function with arguments and no return value
- Function with no arguments and a return value
- Function with arguments and with return value
1. return_type
is the data type of the value that the function will return. If the function doesn't return anything, usevoid
.2. function_name
is the name you give to the function.3. parameters
are the inputs the function accepts.4. function body
contains the code that performs the specific task.5. return result
is used to return a value from the function, whereresult(here we use int d as a RESULT)
should be an expression of the same data type asreturn_type
.
Function with no argument and no return type
#include<iostream.h>
#include<conio.h>
void add();
void add()
{
int a,b,c;
cout<<"Enter the value of a\n";
cin>>a;
cout<<"Enter the value of b\n";
cin>>b;
c=a+b;
cout<<"The value of c\n"<<c;
}
void main()
{
clrscr();
add();
getch();
}
Function with arguments and no return value
#include<iostream.h>
#include<conio.h>
void add(int x,int y);
void add(int x,int y)
{
int c;
cout<<"Enter the value of x\n";
cin>>x;
cout<<"Enter the value of y\n";
cin>>y;
c=x+y;
cout<<"The value of c is\n"<<c;
}
void main()
{
clrscr();
int x,y;
add(x,y);
getch();
}
Function with no arguments and a return value
#include<iostream.h>
#include<conio.h>
int add();
int add()
{
int x,y,c;
cout<<"Enter the value of x\n";
cin>>x;
cout<<"Enter the value of y\n";
cin>>y;
c=x+y;
return c;
}
void main()
{
clrscr();
int d;
d=add();
cout<<"The Result is\n"<<d;
getch();
}
Function with arguments and a return value
#include<iostream.h>
#include<conio.h>
int add();
int add(int x,int y)
{
int c;
cout<<"Enter the value of x";
cin>>x;
cout<<"Enter the value of y";
cin>>y;
c=x+y;
return c;
}
void main()
{
clrscr();
int x,y,d;
d=add(x,y);
cout<<d;
getch();
}