In: Computer Science
Specifications: Create a menu-driven program that finds and displays areas of 3 different objects. The menu should have the following 4 choices: 1 -- square 2 -- circle 3 -- right triangle 4 -- quit
|
Sample Run Program to calculate areas of objects 1 -- square 2 -- circle 3 -- right triangle 4 -- quit 2 Radius of the circle: 3.0 Area = 28.2743 |
I have written two codes separately with output-
code 1- if you want the menu to appear again instead of program getting exit just after one choice this is your code.
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
int choice; //choice variable for the options to choose
float radius,area,length,width; //variable used for
area calculations
do //do loop begins from
here
{
std::cout << "Please to calculate areas of
objects\n"; //menu outputs
std::cout << "1 -- Square\n";
std::cout << "2 -- Circle\n";
std::cout << "3 -- Right triangle\n";
std::cout << "4 -- Quit\n";
std::cin >> choice; //choice input from the menu
switch(choice) //switch case for doing the
operqations on the basis of user choice
{
case 1:
std::cout << "Enter length of square: ";
std::cin >> length;
std::cout << "Area=" << length*length <<
"\n\n";
break;
case 2:
std::cout << "Enter the radius of the circle: ";
std::cin >> radius;
area = 3.142 * radius * radius;
cout << "Area="<<area<< "\n\n";
break;
case 3:
std::cout << "Enter the length of the right triangle:";
std::cin >> length;
std::cout << "Enter the width of the right triangle: ";
std::cin >> width;
std::cout << "Area=" << length*width/2 <<
"\n\n";
break;
case 4:
exit(0);
break;
default: //invalid choice message
cout<<"Invalid choice"<< "\n\n";
}
} while(choice!=4); //while with condition or
quit option number 4
return 0;
}
code 2- if you don't want the menu to reappear and program should just execute one operation and exit.
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
int choice; //choice variable for the options to
choose
float radius,area,length,width; //variable
used for area calculations
std::cout << "Please to calculate areas of
objects\n"; //menu outputs
std::cout << "1 -- Square\n";
std::cout << "2 -- Circle\n";
std::cout << "3 -- Right triangle\n";
std::cout << "4 -- Quit\n";
std::cin >> choice; //choice input from the menu
switch(choice)
{
case 1:
std::cout << "Enter length of square: ";
std::cin >> length;
std::cout << "Area=" << length*length <<
"\n\n";
break;
case 2:
std::cout << "Enter the radius of the circle: ";
std::cin >> radius;
area = 3.142 * radius * radius;
cout << "Area="<<area<<"\n\n";
break;
case 3:
std::cout << "Enter the length of the right triangle:";
std::cin >> length;
std::cout << "Enter the width of the right triangle: ";
std::cin >> width;
std::cout << "Area=" << length*width/2 <<
"\n\n";
break;
case 4:
exit(0);
break;
default:
cout<<"Invalid choice"<<"\n\n";
//invalid choice message
}
return 0;
}
If you still have any query reguarding this code, do reply.