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_typeis the data type of the value that the function will return. If the function doesn't return anything, usevoid.2. function_nameis the name you give to the function.3. parametersare the inputs the function accepts.4. function bodycontains the code that performs the specific task.5. return resultis 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();
}
20231015101258.png)
20231015101316.png)
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();
}
20231015101341.png)
20231015101519.png)
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();
}
20231015101554.png)
20231015101620.png)

20231015101222.png)
20231015101241.png)