square
You will get acquainted with numbers in this lesson. We will first try to make a program to calculate the area of a rectangle and of a circle. We will use numbers with double precision (double type). Double precision refers to a type of floating-point number that has more precision, or more digits to the right of the decimal point, than a single-precision number.
To begin with, create a framework of the function.
func main<main>
{
while 1
{
print("Enter the number of the action:
1. Calculate the area of a rectangle
2. Calculate the area of a circle
3. Exit\n")
switch getch()
{
case '1'
{
print("Specify the width of the rectangle: ")
print("Specify the height of the rectangle: ")
}
case '2'
{
print("Specify the radius of the circle: ")
}
case '3', 27 : break
default : print("You have entered the wrong value!\n\n")
}
}
}
There are two new statements here: while and switch.
The while statement repeats the execution of a code, while the conditional expression is nonzero. In this case, the condition equals 1, that means an endless loop and the command break ,as defined below, causes an exit from the loop.
A loop is one of the three basic logic structures in computer programming. The other two logic structures are selection and sequence.
The switch operator evaluates an expression and looks for the value through the values. case. While the program is waiting for the keystroke, a user thinks of further actions. Now let's take a look at the following line:
case '3', 27 : break
Notice that the possible values separated by commas are enumerated in case. 27 determines the key code Esc. As for the symbol ':', it is denoted by the following line enclosed in braces. In other words, this fragment is equivalent to the following one:
case '3', 27 { break }
The use of braces is often required by Gentee, a usage of the symbol ':' helps you escape piling characters in simple tasks.
To perform calculations we use a string type of a variable for the return values and a double type of two variables in order to store values. You can start by appending:
str input
double width height
Variables of the same type are separated by a comma or a single space.
Now you can perform calculations and get answers. So, to calculate the area of a rectangle we could construct code like this:
print("Specify the width of the rectangle: ")
width = double( conread( input ))
print("Specify the height of the rectangle: ")
height = double( conread( input ))
print("The area of the rectangle: \( width * height )\n\n")
The conread function reads data input by a user. The \(...) operation within the string evaluates the expression enclosed in brackets and inserts data into the string.
To calculate the area of a circle, we can create another example similar to the code, above:
print("Specify the radius of the circle: ")
width = double( conread( input ))
print("The area of the circle: \( 3.1415 * width * width )\n\n")