I am trying to ask the user to select add or subtract and then after it selects add or subtract, then begin to perform the operation, using Main in 5 lines in C++
#include <iostream>
using namespace std;
int main()
{
int a,b,ans;
cout<<"a= ";
cin>>a;
cout<<"b= ";
cin>>b;
cout<<"Enter 1 for addition or 2 for subtraction"<<endl;
cin>>ans;
if(ans==1)
cout<<"a + b = "<<a+b;
else if(ans==2)
cout<<"a - b = "<<a-b;
else
cout<<"Please select 1 or 2";
#include <iostream>
usingnamespace std;
//5 line from main
int main()
{
int a,b,op;
cout<<"Enter a and b\n";cin>>a>>b; cout<<"Would you like to add or subtract: \nEnter\n\t(1) - add \n\t(2) - subtract\n"; cin>>op;
if(op == 1) cout<<"Sum is "<<a+b<<endl;
elseif(op == 2) cout<<"Sum is "<<a-b<<endl;
else cout<<"Wrong input";
}
//5 line from main
int main()
{
int a,b,op;
cout<<"Would you like to add or subtract\nEnter \n\t(1) - add \n\t(2) - subtract\n";cin>>op;
if(op < 1 || op > 2) {cout<<"Wrong input";return 0; }
else {cout<<"Enter a and b"<<endl; cin>>a>>b;
op == 1 ? cout<<a+b<<endl : cout<<a-b;}
}
The assignment states that you must create your own functions. Main should have only a few lines taken because the code would be in the void functions (outside of main) then you simply call them in main. Below is an example:
#include <iostream>
using namespace std;
int main()
{
int a , b ;
int operation ;
cout<<" enter two numbers : " << endl ;
cin>> a ;
cin>> b ;
cout<<"what the operation do you want :" <<endl;
cout<<"1.add " << endl ;
cout<<"2.subtract " << endl;
cin >> operation ;
I need help with declaring a new function and calling them in main() Main should only have 4-5 lines max in it. Outside of main I should have the functions.
I am trying to get the user to select add or subtract 1st, then after selecting option, then perform the operation that was selected between add or subtract.
Your code works. All you have to do is put it in a void function, then call it in main.
For the adding and subtracting, you could make your own function that returns the answer instead. Below is the skeleton for the program. Just fill in the functions with your code.
#include <iostream>
// Function Prototypes.
int Subtract(int, int); // Use this to return the answer to Menu()
int Add(int, int); // Use this to return the answer to Menu()
void Menu(); // Your code goes inside this function
int main()
{
Menu(); // Use 1 line in main to call Menu().
}
void Menu()
{
// Your whole program goes here
}
int Add (int a, int b)
{
// Code that subtracts the two user-input values goes here
}
int Subtract(int a, int b)
{
// Code that adds the two user-input values goes here
}