Adding multiple options in a program.
By declaring an int and prompting the user to select a number from a list we can make a program that goes down one of many paths.
std::cout << "Are you over 18?\n1=yes\n2=no\n3=maybe\n";
int selection;
std::cin >> selection;
if (selection == 1)
{
std::cout << "Access Granted!\n";
}
if (selection == 2)
{
std::cout << "Access Denied!\n";
}
if (selection == 3)
{
std::cout << "Access to the casino cannot be granted to people under 18. You have to confirm your age to gain access!\n";
}
Using a similar strategy to the code above, make a program that asks the user what calculation they want to perform on 2 numbers. Then have them input the 2 numbers they want to perform the calculation on. Perform the calculation they selected and show them the result. Add the ability to sum, subtract, and multiply.
Hint
#include <iostream>
int main()
{
std::cout << "input 2 numbers (seperated by space) to get the sum of them.\n";
float input1, input2;
std::cin >> input1 >> input2;
std::cout << input1 << " + " << input2 << " = " << input1+input2;
}
This program takes 2 inputs and outputs the sum.
The operator for subtraction is -.
The operator for multiplication is *.
Answer
#include <iostream>
int main()
{
int operation;
std::cout << "Choose an operation:\n1. Addition\n2. Subtraction\n3. Multiplication\n";
std::cin >> operation;
float input1, input2;
std::cout << "input 2 numbers (seperated by space) to get the sum of them.\n";
std::cin >> input1 >> input2;
if (operation == 1)
{
std::cout << input1 << " + " << input2 << " = " << input1+input2;
}
if (operation == 2)
{
std::cout << input1 << " - " << input2 << " = " << input1-input2;
}
if (operation == 3)
{
std::cout << input1 << " * " << input2 << " = " << input1*input2;
}
}