Switch case exercise
In this exercise, we will create a program that calculates the area of various geometrical figures such as Circle, Triangle, Trapezoid, Square, and Rectangle using switch/case statements.
Exercise:
- Write a program to calculate the area of different geometrical figures like Circle, triangle, trapezoid, square, and rectangle.
- The program should ask the user to enter the code for which the user wants to find out the area.
→ ‘t’ for triangle
→ ‘z’ for trapezoid
→ ‘c’ for circle
→ ‘s’ for square
→ ‘r’ for rectangle
The formula is shown in Figure 1.
When the user enters the code ‘t’ (it’s a triangle), it shows the triangle information. To calculate the area of the triangle, you need more information. You need to know the value of base and height. So, you should ask the user to enter the values of base and height, then you have to calculate the area and print the area, like that.
If the code is ‘z’, it is for trapezoid, and you have to ask base1, base2, height, and calculate the area according to the above formula.
Figure 2 shows the area of a rectangle formula.
Sample Output
A sample program output should follow the format shown in Figure 3, which displays the available codes and their corresponding shapes to the user.
First, the program should print those messages to the user with the codes.
Now the user enters the code c, then it prints “circle area calculation,” and it has to ask the user to “Enter the radius value” in this case.
Here the user enters a radius value is -9, and we can see that it prints ‘Radius cannot be negative’, as shown in Figure 4. So, all these error handling messages you should take care.
When the user enters the code t, it prints “Triangle area calculation”. Then it asks the user to Enter the base value and height. Then it calculates the value and prints the area of the triangle Output.
Here, I enter the base value as 9 and the height value as .7. It shows Area = 3.150000, as shown in Figure 5.
Try to implement this for all other geometrical figures. I will implement this in the following article using switch/case statements.
Get the Full Course on Microcontroller Embedded C Programming Here.
FastBit Embedded Brain Academy Courses
Click here: https://fastbitlab.com/course1