In C programming, the **If...Else** statement is used to execute a block of code only if a specified condition is met. It is the primary way to control the flow of a program. Without decision-making statements, a program would always run the same way, line by line, without reacting to user input or data changes.
The if statement is the simplest form of decision-making. If the condition inside the parentheses evaluates to **true** (non-zero), the code block inside the curly braces {} is executed.
Example: Checking if 20 is greater than 18.
The else statement is used to specify a block of code that should run if the if condition is **false**. This creates a "fork in the road" for your program.
When you have more than two possible paths, you use else if. It allows you to check multiple conditions sequentially. The program will execute the code for the **first** condition that is true and skip the rest.
You can also place an if statement inside another if statement. This is known as **Nesting**. It is useful when one condition depends on the success of a previous condition.
C provides a compact way to write an if-else statement using the Ternary Operator. It consists of three operands and is often used to assign values based on a condition.
Syntax: variable = (condition) ? expressionTrue : expressionFalse;
To choose the right statement for your logic, refer to this summary table:
| Statement | Purpose |
|---|---|
if |
Executes code if one condition is true. |
else |
Executes code if the same condition is false. |
else if |
Tests a new condition if the first one is false. |
switch |
Tests a variable against a list of constant values. |
if (x = 5) assigns 5 to x and always returns true. Use if (x == 5) for comparison.if block, you **must** use {}. Even for one line, using them is a best practice.if (x > y); will terminate the if statement immediately, and the following block will run regardless of the condition.if an else belongs to.