01
Flow of Control and Operators
By default, statements execute in sequence. Control structures change this:
- Selection (
if,if-else,switch) — choose which code to execute based on a condition. - Repetition (
while,for,do) — repeat code while a condition holds.
Relational and Equality Operators
< less than > greater than
<= less than/equal >= greater than/equal
== equal to != not equal to
Logical Operators
! NOT (unary)
&& AND (binary)
|| OR (binary)
In C: false = 0, true = any non-zero value.
Operator Associativity
+ - ++ -- ! right to left
* / % left to right
+ - left to right
< <= > >= left to right
== != left to right
&& left to right
|| left to right
= += -= *= /= right to left
02
Conditional Statements
The if Statement
if (condition)
statement;
If the condition is true (non-zero), the statement executes; otherwise skipped.
The if-else Statement
if (condition)
statement1;
else
statement2;
Nested if-else:
if (x == 50) {
if (y >= 120) {
sum = x + y;
printf("Sum: %d", sum);
} else {
diff = x - y;
printf("Difference: %d", diff);
}
} else {
printf("Next time");
}
The switch Statement
switch (expression) {
case constant1:
statement;
break;
case constant2:
statement;
break;
default:
statement;
}
switchexpression must evaluate tointorchar(not float or string).casevalues must be constants.breakexits the switch; without it, execution "falls through" to the next case.defaulthandles unmatched values.
Grouping cases (intentional fall-through):
switch (QUIZ) {
case 10:
case 9: printf("A"); break; // 9 or 10 → A
case 8: printf("B"); break;
case 7: printf("C"); break;
default: printf("F");
}
03
Unconditional Transfer: break and continue
break
Two uses:
- Exits a
switchafter a matching case. - Immediately exits the innermost loop.
while (1) {
scanf("%lf", &x);
if (x < 0.0)
break;
printf("%f\n", sqrt(x));
}
continue
Skips the rest of the current loop iteration and jumps to the next iteration.
do {
scanf("%d", &num);
if (num < 0)
continue;
printf("%d", num);
} while (num != 100);
04
Loop Structures
while Loop
Condition checked before each iteration. If false initially, body never runs.
while (condition)
statement;
// Example:
while (number != 0) {
scanf("%d", &number);
sum += number;
}
for Loop
for (initialization; condition; increment)
statement;
- Initialization — runs once before the loop.
- Condition — checked before each iteration.
- Increment — runs after each iteration.
for (x = 100; x != 65; x += 5) {
z = sqrt(x);
printf("Square root of %d is %f", x, z);
}
Multiple variables (comma operator):
for (x = 0, y = 0; x + y < 10; x++) { ... }
do-while Loop
Body runs at least once — condition checked after each iteration.
do {
statement;
} while (condition);
// Example:
do {
printf("Enter a number: ");
scanf("%d", &a);
sum = sum + a;
} while (a != 0);
printf("The sum is %d", sum);
05
Practice Exercises — Lesson 4
06
Try It: Control Structures
Change the grade value and see which branch runs. Then modify the loop limits.