If statements are fundamental control structures in programming that allow algorithms to make decisions based on certain conditions. In pseudocode, we use if statements to describe these decision-making processes.
The basic syntax for an if statement in pseudocode is:
IF condition THEN
statement(s)
END IF
Example:
IF age >= 18 THEN
OUTPUT "You are eligible to vote."
END IF
This pseudocode checks if the age is 18 or older and outputs a message if true. For more information on variables, refer to the Variables in Pseudocode guide.
When you want to execute different code blocks based on whether a condition is true or false, use an if-else statement:
IF condition THEN
statement(s)
ELSE
statement(s)
END IF
Example:
IF score >= 60 THEN
OUTPUT "You passed the exam."
ELSE
OUTPUT "You failed the exam."
END IF
For multiple conditions, use else-if statements:
IF condition1 THEN
statement(s)
ELSE IF condition2 THEN
statement(s)
ELSE
statement(s)
END IF
Example:
IF grade >= 90 THEN
OUTPUT "A"
ELSE IF grade >= 80 THEN
OUTPUT "B"
ELSE IF grade >= 70 THEN
OUTPUT "C"
ELSE
OUTPUT "F"
END IF
You can also nest if statements within each other:
IF condition1 THEN
IF condition2 THEN
statement(s)
ELSE
statement(s)
END IF
ELSE
statement(s)
END IF
Example:
IF is_raining THEN
IF has_umbrella THEN
OUTPUT "Use your umbrella"
ELSE
OUTPUT "Wear a raincoat"
END IF
ELSE
OUTPUT "Enjoy the weather"
END IF
You can use logical operators (AND, OR, NOT) to create more complex conditions:
IF age >= 18 AND has_id THEN
OUTPUT "You can enter the venue."
END IF
IF is_weekend OR is_holiday THEN
OUTPUT "The store is closed."
END IF
IF NOT is_member THEN
OUTPUT "You need a membership to access this area."
END IF
For more information on input and output operations, check the Input/Output in Pseudocode guide.
Remember, the goal of pseudocode is to communicate logic clearly. While the exact syntax may vary, the important thing is to convey the decision-making process in your algorithm.