If Statement
The most commonly used statement that uses comparison operators is the if statement. The structure of the if statement in pseudo code is as follows:
if <comparison> is true
- do commands
It can also be enlarged so that you can do something if the comparison is false:
if <comparison> is true
- do commands
else <comparison> is not true
- do other commands
The structure can enlarged even further by having a series of comparisons. What happens if that the first if executes statements is true. If it is false then check to see if the next comparison is true and execute commands. If both the if statements are not true then execute at end.
if <comparison 1> is true
- do commands
else if <comparison> is not true then if <comparison 2> is true
- do other commands
else if <comparison1 > is not true and <comparison 2> is not true
- do other commands
The following is a basic example of how if statements work.
var number = 8; if (number > 5); print ("number is more than 5"); if (number == 6) print ("the number is equal to 6"); else print ("the number is not equal to 6");
The first line
if (number > 5);
Compares to see if the contents of variable number is more than 5. if it is then it executes the following command if true:
print ("number is more than 5");
The next line compare the number to see if it is equal to 6
if (number == 6)
If this is true then it executes the following command
print ("the number is equal to 6");
The next lines are executed if the above if statement is false which it is as number is not equal to 6
else print ("the number is not equal to 6");
The following example allows you to enter a number and output whether it is positive, negative or is 0
var readline = imports.readline; var number_input = readline.readline("Enter number >"); if (number_input > 0) print("Number is a positive integer"); else if (number_input < 0) print("Number is a negative integer"); else print("Number is 0");
The following lines import the readline module that allows user input on the console. The input is placed into the variable number
var readline = imports.readline; var number_input = readline.readline("Enter number >");
As explained earlier, if the contents of the number_input is more than 0 then the print statement is executed.
if (number_input > 0) print("Number is a positive integer");
If the last if statement is false i.e. number_input is not higher than 0 (signified by else) then check to see if number_input is less than 0