I'm writing a program that calculates the area of a circle, triangle, rectangle. However, the program is not supposed to accept negative values for radius, length, width, ...etc. I've seen how to do it with if / else statements, but can't figure it out with switch statements. Any help would be appreciated.
#include <iostream>
#include <iomanip>
#incldue <cmath>
usingnamespace std;
int main()
{
int radius, length, width, height, base, choice;
double cirArea = 0;
rectArea = 0;
triArea = 0;
const in
Area_of_Circle = 1,
Area_of_Rectangle = 2,
Area_of_Triangle = 3,
Quit = 4;
cout << "This program will calculate the area of a circle, rectangle,";
cout << " or triangle.\n";
cout << "Please select from the menu choices below.\n";
cout << "Enter the corresponding number with the calculation";
cout << " you would like to perform.\n";
cout << "1. Area of a Circle\n";
cout << "2. Area of a Rectangle\n";
cout << "3. Area of a Triangle\n";
cout << "4. Quit\n";
cin >> choice;
switch (choice)
{
case 1: cout << "You chose 1 to find the area of a circle.\n";
cout << "Please enter the radius of the circle.\n";
cin >> radius;
cirArea = 3.14159 * (radius * radius)
cout << "The are of the circle is " << cirArea << "." << endl;
break;
Then the code continues on the same way for the other menu options, with a default statement that throws out an error message if the user enters any other number other 1-4 for the menu options. Again, any help would be appreciated. Thanks
switch (choice) {
case 1:
cout << "Please enter the radius of the circle.\n";
cin >> radius;
cirArea = 3.14159 * (radius * radius)
cout << "The are of the circle is " << cirArea << "." << endl;
break;
case 2:
// code to do a rectangle
break;
case 3:
// code to do a triangle
break;
case 4:
quit = true;
break;
default:
// code to tell user the input is invalid
break;
}
Some good habits to follow when writing switch statements:
- If the code should not flow from one case into the next one, then use a break statement, even with the last case in the statement (such as the default one above). This way if you change the order or add a new case, the code will still work.
- If the code should flow from one case into the next, then put a comment at the end of the first case stating that you're doing in deliberately. I use // fallthrough .