Debian Codegraph @

examples/tiny/samples/calculate_areas.tiny

raw
1 /* Compute the area of a selected shape in TINY.
2 Interaction:
3 - First, prompt for the shape type: enter one of "s", "c", "r", or "t"
4 for square, circle, rectangle, or triangle, respectively.
5 - Then, prompt only for the dimensions required for that shape.
6 - All dimensions must be integers > 0 (non-positive values are rejected).
7 - The program prints the area for the selected shape and exits.
8 */
9
10 float area_square(float side) {
11 return side * side;
12 }
13
14 float area_circle(float radius) {
15 float pi := 3.141592653589793;
16 return pi * radius * radius;
17 }
18
19 float area_rectangle(float width, float height) {
20 return width * height;
21 }
22
23 float area_triangle(float base, float height) {
24 return 0.5 * base * height;
25 }
26
27 int main() {
28 string shape;
29
30 /* Prompt for shape type */
31 write "Enter shape (s=square, c=circle, r=rectangle, t=triangle): ";
32 read shape;
33
34 /* Square */
35 if shape = "s" then
36 int side;
37 write "Enter side (integer > 0): ";
38 read side;
39 if side <= 0 then
40 write "Error: side must be an integer > 0"; write endl;
41 return 1;
42 end
43 write "Square area: "; write area_square(side); write endl;
44 return 0;
45 end
46
47 /* Circle */
48 if shape = "c" then
49 int radius;
50 write "Enter radius (integer > 0): ";
51 read radius;
52 if radius <= 0 then
53 write "Error: radius must be an integer > 0"; write endl;
54 return 1;
55 end
56 write "Circle area: "; write area_circle(radius); write endl;
57 return 0;
58 end
59
60 /* Rectangle */
61 if shape = "r" then
62 int width;
63 int height;
64 write "Enter width (integer > 0): ";
65 read width;
66 if width <= 0 then
67 write "Error: width must be an integer > 0"; write endl;
68 return 1;
69 end
70 write "Enter height (integer > 0): ";
71 read height;
72 if height <= 0 then
73 write "Error: height must be an integer > 0"; write endl;
74 return 1;
75 end
76 write "Rectangle area: "; write area_rectangle(width, height); write endl;
77 return 0;
78 end
79
80 /* Triangle */
81 if shape = "t" then
82 int base;
83 int height;
84 write "Enter base (integer > 0): ";
85 read base;
86 if base <= 0 then
87 write "Error: base must be an integer > 0"; write endl;
88 return 1;
89 end
90 write "Enter height (integer > 0): ";
91 read height;
92 if height <= 0 then
93 write "Error: height must be an integer > 0"; write endl;
94 return 1;
95 end
96 write "Triangle area: "; write area_triangle(base, height); write endl;
97 return 0;
98 end
99
100 /* Unknown shape */
101 write "Error: unknown shape; enter one of s, c, r, t"; write endl;
102 return 1;
103 }