Menu creation using switch-case – CSKC
Sign In

Search

Code Learning #CPP#1978    siteicon   siteicon  

Menu creation using switch-case

Creating a menu using switch case and run appropriate code piece based on menu selection.

Learning Objectives

  • Menu creation using switch case.
  • Use of cmath header for sqrt() function
  • Use of exit() function

Program Approach

  • Codes for different actions of area, perimeter and diagonal shall be written in different cases as given by the menu choices.

Source Code

TC++ #1978

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

Code Understanding

cout << “1. Find Area ” <<endl;
cout << “2. Find Perimeter ” <<endl;
cout << “3. Find Diagonal ” <<endl;
cout << “4. Exit ” << endl;
cout << “Enter your choice : ” ;
cin >> c ;
This is a simple way to show a menu and collect the option number in an integer variable.

case 1: cout << “Area = ” << s*s ; break ;
case 2: cout << “Perimeter = ” << 4*s ; break ;
case 3: cout << “Diagonal = ” << s*sqrt(2); break ;
Different functional formulas are used as per the menu choice.

case 4:exit(0);
This is a case where exit(0) function is used. exit(0) is equivalent to returning to operating system directly with 0 code passed to it. 0 code usually represent the successful completion of program without any known error.

default: cout << “Wrong Menu Choice” ;
Here we come out with option of wrong menu choice when user presses any key not present in the menu.

Notes

  • These kind of programs are usually written in do-while loop, so that if wrong menu choice is there the menu can be shown again.

Common Errors

  • Formula as per menu choice should be individually tested. Such programs often suffer from incorrect placement of formulas for a particular menu choice.


Suggested Filename(s): menu-using-switch.cpp



Share

Created: 28-Dec-2017 15:15 | Updated: 15-Sep-2018 11:59|