If/Else
If/Else Statement in Computer Programming
In computer programming, the if/else
statement is a fundamental control flow structure that allows a program to execute certain blocks of code based on whether a specified condition is true or false. If the condition evaluates to true, the block of code inside the if
part is executed. If the condition is false, the code inside the else
part is executed instead. This allows for decision-making processes within the code.
Example in Python
This Python example checks if the age
variable is greater than or equal to 18. If true, it prints that you are eligible to vote. Otherwise, it prints that you are not eligible to vote.
Example in C#
In this C# example, the program checks if the number
variable is greater than 0. If the condition is true, it prints that the number is positive. If false, it prints that the number is not positive.
ElseIf Statement
While if/else structures are essential for basic decision-making, the elseif (or else if) clause introduces more nuanced control. It allows you to specify an additional condition(s) to test if the initial if condition is false. The elseif block is executed only if its condition is true and all preceding if or elseif conditions were false. This is particularly useful for checking multiple conditions sequentially.
Example in Python
This Python example determines whether someone is a minor, an adult, or a senior based on their age. The elif clause is used here to add the additional condition for being an adult.
Example in C#
In this C# example, the program categorizes a score as "Fail," "Good," or "Excellent." It uses else if to add the condition for scoring 'Good.'
Last updated
Was this helpful?