IF Statements: Making Decisions in Code
IF statements are fundamental control flow structures in programming. They allow your program to execute different blocks of code based on whether a specific condition is true or false.
The Basic IF Structure
The simplest form of an IF statement checks a condition. If the condition evaluates to true, the code inside the IF block is executed.
Syntax (Conceptual)
IF condition THEN
-- Code to execute if condition is TRUE
END IF
Most programming languages use a similar structure, often with parentheses around the condition and curly braces or indentation to define the code block.
Example in Pseudocode:
SET temperature = 25
IF temperature > 20 THEN
PRINT "It's a warm day!"
END IF
In this example, since 25 is indeed greater than 20, the message "It's a warm day!" will be displayed.
IF-ELSE Statements
What if you want to do something else when the condition is false? That's where the ELSE clause comes in. An IF-ELSE statement provides an alternative block of code to execute when the IF condition is not met.
Syntax (Conceptual)
IF condition THEN
-- Code to execute if condition is TRUE
ELSE
-- Code to execute if condition is FALSE
END IF
Example in Pseudocode:
SET age = 15
IF age >= 18 THEN
PRINT "You are an adult."
ELSE
PRINT "You are a minor."
END IF
Here, because 15 is not greater than or equal to 18, the ELSE block will be executed, printing "You are a minor."
IF-ELSE IF-ELSE Statements
You can chain multiple conditions using ELSE IF (or ELIF in some languages). This allows for more complex decision-making with multiple possibilities.
Syntax (Conceptual)
IF condition1 THEN
-- Code for condition1
ELSE IF condition2 THEN
-- Code for condition2
ELSE IF condition3 THEN
-- Code for condition3
ELSE
-- Code if none of the above conditions are met
END IF
Example in Pseudocode:
SET score = 75
IF score >= 90 THEN
PRINT "Grade: A"
ELSE IF score >= 80 THEN
PRINT "Grade: B"
ELSE IF score >= 70 THEN
PRINT "Grade: C"
ELSE
PRINT "Grade: D or F"
END IF
With a score of 75, the program will check the conditions in order. It's not >= 90, not >= 80, but it IS >= 70, so it prints "Grade: C".
Interactive Example
Enter a number to see how IF-ELSE IF statements work:
Common Operators in Conditions
Conditions typically involve comparison operators:
==: Equal to!=: Not equal to>: Greater than<: Less than>=: Greater than or equal to<=: Less than or equal to
You can also use logical operators to combine conditions:
AND(or&&) : Both conditions must be trueOR(or||) : At least one condition must be trueNOT(or!) : Reverses the truth value of a condition