Owner`s manual

92
6.2.4 Using selection statements
Using the “if” selection statement
You can use the “if” statement to tell the computer to shift the flow of control if certain
conditions are met. The “if” statement has two basic formats.
1. if (condition) statement.
Here, the statement is executed if the condition is met (true = any value other than 0),
and not executed if the condition is not met (false = 0).
2. if (condition) statement 1
else statement 2
In this case, statement 1 is executed if the condition is met (true = any value other
than 0), while statement 2 is executed if the condition is not met (false = 0).
The “if – else” statement may contain multiple statements for the “if” and the “else”
statements. In the following example, please also note the proper format for easy
reading.
Note that the statements are aligned and also note the position of the braces.
if (condition){
Statement 1
Statement 2
}
else{
Statement 3
Statement 4
}
A program to solve quadratic equations
Here, we will create a program that produces two solutions for the following quadratic
equation: ax
2
+ bx + c = 0 (a 0)
In the above equation, it is assumed that a, b and c are real numbers.
The solution for the formula is:
- b ± (b
2
– 4ac)
x=
2a
Also, the following is the discriminant which determines the following concerning the
solutions of the above equation:
D = b
2
4ac
D>0 – Two different real solutions
D=0 – Single real solution
D<0 – Two different imaginary numbers (conjugate complex numbers)
In the program listed below, the discriminantr is used in the condition of a selection
statement with one operation being performed if D0 and another being performed
when D<0.