If-else syntax

The if-else statement is a control structure that executes different program parts depending on a condition. If the condition is met, the program part from the if-branch is executed, if the condition is not met, the else part is executed.

if (condition)
	// if condition is true, this block of code will be executed
if (condition) {
	// if condition is true, this block of code will be executed
} else {
	// if condition is false, this block of code will be executed
}
if (condition) {
	// if condition is true, this block of code will be executed
} else if (condition2) {
	// if condition2 is true, this block of code will be executed
} else {
	// neither condition nor condition2 is true
}
  1. The condition is a boolean expression that evaluates to either true or false. It can be any expression or combination of expressions that resolves to a boolean value. If the condition is true, the code block within the if statement will be executed. If the condition is false, the code block within the else statement (if present) will be executed.
  2. The code block within the if statement or the else statement is enclosed within curly braces {}. This block can contain one or more statements or even nested if-else statements.
  3. The else statement is optional. If it is omitted, and the condition is false, the program will simply continue execution after the if statement.
  4. You can also have multiple if-else statements chained together, known as an “else if” ladder, to handle different conditions. This allows you to test multiple conditions and execute different code blocks based on the first condition that evaluates to true.