Skip to content

Module 3 · Decisions and Loops — topic 1 of 5

Conditional Statements (if, else if, else)

if statements let a program choose what to do based on a condition. Learn if, if-else, else-if ladders, nesting, and how C decides what counts as true.

Beginner 15 min read·Lesson 11 of 37 in C Programming

Learning objectives

  • Write if, if-else and else-if ladders
  • Explain how C treats any non-zero value as true
  • Avoid the dangling-else and missing-brace bugs

Definition

A selection statement evaluates a scalar controlling expression; if the value compares unequal to zero the associated statement executes, otherwise the optional else statement executes.

Introduction

Real programs react to data: a passing mark prints “Pass”, a wrong password is rejected, a low balance blocks a withdrawal. The if statement is how a program makes those decisions.

C has no special boolean type in conditions: any expression can be a condition. Zero means false and every other value means true. Comparisons like marks >= 40 simply produce 1 or 0.

Why it matters

Selection is one of the three building blocks of every algorithm. Grading systems, menu-driven programs, input validation and game logic all depend on correct conditions.

Off-by-one conditions (> instead of >=) and missing braces are among the most common bugs in lab exams. Writing conditions carefully is worth the effort.

Detailed explanation

if (condition) statement runs the statement only when the condition is non-zero. Add else statement to run an alternative when it is zero.

An else-if ladder tests conditions in order and runs the first branch whose condition is true; the final else handles everything else. Order matters: put the most specific or highest thresholds first.

Without braces, if controls exactly one statement. A block { ... } groups several statements into one. Using braces always avoids the classic bug where an indented second line is not actually inside the if.

Dangling else: an else attaches to the nearest unmatched if, regardless of indentation. Braces make the intended pairing explicit.

ExpressionValueTreated as
5 > 31true
5 == 30false
77true
00false
-1-1true
ptr (non-NULL)addresstrue

Syntax

C
if (condition) {
/* runs when condition != 0 */
} else if (other_condition) {
/* runs when the first is false and this is true */
} else {
/* runs when every condition is false */
}
  • Parentheses around the condition are required.
  • else if and else are optional.
  • Use braces even for single statements.

Code examples

Even or odd

C
#include <stdio.h>
int main(void) {
int n = 17;
if (n % 2 == 0) {
printf("%d is even\n", n);
} else {
printf("%d is odd\n", n);
}
return 0;
}
Output
17 is odd

Any non-zero value is true

C
#include <stdio.h>
int main(void) {
int items = 3;
if (items)
printf("Cart has %d items\n", items);
if (!0)
printf("!0 is %d\n", !0);
return 0;
}
Output
Cart has 3 items
!0 is 1

More examples

Grade calculator with an else-if ladder

C
#include <stdio.h>
char grade_for(int marks) {
if (marks < 0 || marks > 100) return '?';
if (marks >= 90) return 'O';
else if (marks >= 80) return 'A';
else if (marks >= 70) return 'B';
else if (marks >= 60) return 'C';
else if (marks >= 40) return 'P';
else return 'F';
}
int main(void) {
int tests[] = {95, 80, 79, 40, 39, 105};
for (int i = 0; i < 6; i++)
printf("%3d -> %c\n", tests[i], grade_for(tests[i]));
return 0;
}
Output
 95 -> O
 80 -> A
 79 -> B
 40 -> P
 39 -> F
105 -> ?

Step-by-step explanation

  • The first if rejects invalid marks before any grading happens (input validation).
  • The ladder checks thresholds from highest to lowest, so 95 matches >= 90 and stops.
  • 80 fails >= 90 but matches >= 80, showing the boundary is inclusive.
  • 39 falls through every test to the final else and gets 'F'.
  • The test array deliberately includes boundary values — the best way to test conditions.

Expected output

Running “Grade calculator with an else-if ladder” prints exactly:

TextOutput
95 -> O
80 -> A
79 -> B
40 -> P
39 -> F
105 -> ?

Practical applications

  • ATM software checks PIN, balance and daily limit before dispensing cash.
  • Compilers decide which code to generate from the types of operands.
  • Login systems branch on whether credentials are valid, locked or expired.

Best practices

  • Always use braces for if and else bodies.
  • Test boundary values (exactly 40, 39, 100, 0) for every condition.
  • Validate input at the top of a function and return early.

Common mistakes

Missing braces around two statements

Avoid

if (balance < 0)
printf("Overdrawn\n");
balance = 0;

Prefer

if (balance < 0) {
printf("Overdrawn\n");
balance = 0;
}

Only the first line belongs to the if. balance = 0; always runs, whatever the indentation suggests.

Semicolon after the condition

Avoid

if (x > 10);
printf("big\n");

Prefer

if (x > 10)
printf("big\n");

The semicolon is an empty statement that becomes the if body, so the printf always runs.

Ladder in the wrong order

Avoid

if (m >= 40) g = 'P';
else if (m >= 90) g = 'O';

Prefer

if (m >= 90) g = 'O';
else if (m >= 40) g = 'P';

A mark of 95 matches >= 40 first, so the higher grade is unreachable.

Important notes

  • if (x = 0) assigns and is always false; -Wall warns about assignments used as conditions.
  • Comparing floating-point values for exact equality inside conditions is unreliable; compare with a tolerance.

Key takeaways

  • if runs code when the condition is non-zero; else handles the zero case.
  • An else-if ladder runs only the first true branch, so order thresholds carefully.
  • Braces prevent the missing-brace and dangling-else bugs.

Try it yourself

  1. 1
    Read a year and print whether it is a leap year (divisible by 4 and not by 100, or divisible by 400).
  2. 2
    Read three numbers and print the largest using nested if statements, then again using &&.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

5 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerWhat is the bug? `if (x > 10); printf("big");`
Practise this topic