Making Decisions in C
By default, C statements execute sequentially from top to bottom. Branching statements allow your code to choose different execution paths based on runtime conditions.
true condition in an if statement?The Simple if Statement
An if statement executes a block of code only if the specified condition evaluates to true (non-zero). If false, the block is completely skipped.
Syntax & Mechanics
If there is only a single statement inside the if block, curly braces {} are optional, but using them is best practice to prevent bugs.
Interactive Lab: Temperature Alert
Test how a single if statement responds to input values.
The if-else Statement
Use if-else when you have two mutually exclusive choices: execute Action A if the condition is true, or Action B if the condition is false.
Interactive Code Tracer: Voting Eligibility
Nested if-else & The Dangling Else
An if or else block can contain another complete if-else structure. Beware of the Dangling Else ambiguity!
⚠️ The Dangling Else Trap
In C, an else clause is always paired with the nearest preceding if that does not already have an else, regardless of indentation!
{} to enforce clear scope!Interactive Admission Test
The if-else Ladder
When testing a single variable or expression against multiple sequential ranges, an if-else if-else ladder evaluates conditions top-to-bottom until a true match is found.
Interactive Grade Calculator
marks >= 90 Grade A+marks >= 80 Grade Amarks >= 70 Grade Bmarks >= 60 Grade Celse Grade FCommon Branching Pitfalls in C
Watch out for these frequent logical bugs that compile cleanly but produce wrong behavior!
Assignment vs Equality
Accidentally writing if (x = 5) instead of if (x == 5) assigns 5 to x, which evaluates as TRUE!
Extra Semicolon Bug
Placing a semicolon right after if(...) ; creates an empty statement, causing the following block to ALWAYS run!
Best Practice: Braces
Always use curly braces {} even for single-line blocks to improve code readability and maintainability.