For Example:
We are creating a user defined function for addition.
#include<iostream>
using namespace std;
{
cout<<"Enter the numbers you want to add"<<endl;
cin>>x;
cin>>y;
cout<<"Addition is = "<<x+y<<endl;
return x;
}
Call That User Defined Function In Your Main Function.
int main()
{
int x; int y;
add(x,y);
return 0;
}
Now Let me further explain you for your better understanding
Lets create user defined function for addition as well as subtraction and then calling them at user's choice.
First Create user defined Functions.
Funtion For Addition:
#include<iostream>
using namespace std;
int add(int x, int y)
{
cout<<"Enter the numbers you want to add"<<endl;
cin>>x;
cin>>y;
cout<<"Addition is = "<<x+y<<endl;
return x;
}
Function For Subtraction:
int sub(int x, int y)
{
cout<<"Enter the numbers you want to subtract"<<endl;
cin>>x;
cin>>y;
cout<<"Subtraction is = "<<x-y<<endl;
return x;
}
Calling Them In Your Main Function at user's Choice:
int main()
{
int a;
cout<<"Press 1. For Addition"<<endl<<endl<<"Press 2. For Subtraction"<<endl;
cin>>a;
if (a==1)
{
system("CLS"); // using this for new screen to appear.
int x; int y;
add(x,y);
}
else if (a==2)
{
system("CLS");
int x; int y;
sub(x,y);
}
return 0;
}
Your Final Structure of the program will be like this
#include<iostream>
using namespace std;
int add(int x, int y)
{
cout<<"Enter the numbers you want to add"<<endl;
cin>>x;
cin>>y;
cout<<"Addition is = "<<x+y<<endl;
return x;
}
int sub(int x, int y)
{
cout<<"Enter the numbers you want to subtract"<<endl;
cin>>x;
cin>>y;
cout<<"Subtraction is = "<<x-y<<endl;
return x;
}
int main()
{
int a;
cout<<"Press 1. For Addition"<<endl<<endl<<"Press 2. For Subtraction"<<endl;
cin>>a;
if (a==1)
{
system("CLS"); // using this for new screen to appear.
int x; int y;
add(x,y);
}
else if (a==2)
{
system("CLS");
int x; int y;
sub(x,y);
}
return 0;
}
easy to understand (very nice)
ReplyDeleteThanks Bro
Delete