Lesson 3 of 5

Control Flow: Conditions and Loops

Controlling the Path of Execution

Control-flow statements let a C program make choices and repeat work.

The if Statement

The condition goes inside parentheses, and the code to run goes inside curly braces.

int marks = 72;

if (marks >= 80) {
    printf("Grade: A+\n");
} else if (marks >= 70) {
    printf("Grade: A\n");
} else {
    printf("Keep practising\n");
}

Comparison and Logical Operators

  • == equal, != not equal.
  • >, <, >=, <= for ordering.
  • && logical AND, || logical OR, ! logical NOT.

In C there is no separate boolean type by default. The value 0 means false and any non-zero value means true.

The while Loop

A while loop repeats as long as its condition stays true.

int count = 1;
while (count <= 5) {
    printf("Count: %d\n", count);
    count++;
}

The count++ step is vital. Without it the condition never becomes false and the loop runs forever.

The for Loop

A for loop packs the start, condition, and step into one line. It is ideal when you know how many times to repeat.

for (int i = 0; i < 5; i++) {
    printf("i is %d\n", i);
}

This runs five times, with i taking the values 0, 1, 2, 3, 4.

The switch Statement

A switch compares one value against several fixed cases. The break keyword stops execution from falling through into the next case.

int day = 3;
switch (day) {
    case 1:
        printf("Monday\n");
        break;
    case 3:
        printf("Wednesday\n");
        break;
    default:
        printf("Another day\n");
}
Forgetting break inside a switch causes “fall-through”, where execution continues into later cases. This is a frequent and confusing bug.
Next
How did you find this lesson?

Discussion

0
To join the discussion, comment and react, log in or create an account.

No comments yet — be the first to leave one!