if Statements and Control Flow
If Statements and Control Flow
What are If Statements?
- If statements are used in programming to perform different actions based on different conditions.
- They are a way to make decisions in your code based on the evaluation of one or more conditions.
- They can be combined with logical operators (AND, OR, and NOT) to make more complex decision-making scenarios.
Structure of If Statements
- An if statement starts with the keyword
if
followed by a condition enclosed in parentheses()
. - The condition is a boolean expression that evaluates to either
true
orfalse
. - The controlled code block, the code to be executed if the condition is
true
, is enclosed in curly braces{}
. This code block is often referred to as the “if block”.
Else Clause
- An else clause can be added to an if statement to specify a block of code to be executed if the condition is
false
. - The else clause starts with the keyword
else
followed by the additional code block enclosed in curly braces{}
.
Else If Statement
- Else if statement is used to specify a new condition to test if the first condition is
false
. - You can have as many else if statements as you want in an if statement, but they must come before the else clause.
Nested If Statements
- Nested if statements means an if statement inside another if statement.
- They are used for testing multiple conditions where each condition is nested inside the condition before it.
Control Flow
- Control flow in programming refers to the order in which the code is executed.
- By using if statements, programs can control what code is executed based on specific conditions being met.
Importance of Condition Order
- The order of conditions in an if statement is important.
- Conditions are checked in order from top to bottom, so the first condition that is
true
will be executed. - Once a condition is found to be
true
, the program will execute the corresponding code block and will not check the remaining conditions.
Comparison Operators
- Comparison operators are used in the conditions of if statements.
- They include equality (
==
), inequality (!=
), greater than (>
), less than (<
), greater than or equal to (>=
), and less than or equal to (<=
). - These operators compare two values and return
true
orfalse
.