§ — — Computer Programming 1
By default, statements execute in sequence. Control structures change this:
if, if-else, switch) — choose which code to execute based on a condition.while, for, do) — repeat code while a condition holds.< less than > greater than
<= less than/equal >= greater than/equal
== equal to != not equal to
! NOT (unary)
&& AND (binary)
|| OR (binary)
In C: false = 0, true = any non-zero value.
+ - ++ -- ! right to left
* / % left to right
+ - left to right
< <= > >= left to right
== != left to right
&& left to right
|| left to right
= += -= *= /= right to left
if Statementif (condition)
statement;
If the condition is true (non-zero), the statement executes; otherwise skipped.
if-else Statementif (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");
}
switch Statementswitch (expression) {
case constant1:
statement;
break;
case constant2:
statement;
break;
default:
statement;
}
switch expression must evaluate to int or char (not float or string).case values must be constants.break exits the switch; without it, execution "falls through" to the next case.default handles 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");
}
breakTwo uses:
switch after a matching case.while (1) {
scanf("%lf", &x);
if (x < 0.0)
break;
printf("%f\n", sqrt(x));
}
continueSkips 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);
while LoopCondition checked before each iteration. If false initially, body never runs.
while (condition)
statement;
// Example:
while (number != 0) {
scanf("%d", &number);
sum += number;
}
for Loopfor (initialization; condition; increment)
statement;
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 LoopBody 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);
ProReviewer — locked
Drills, code labs, and full solutions.
ProReviewer — locked
Drills, code labs, and full solutions.
ProReviewer — locked
Drills, code labs, and full solutions.
Change the grade value and see which branch runs. Then modify the loop limits.
Done with this module? Track it — your progress shows on the subject list.
Up next
Lesson 5: Arrays→←Previous: Lesson 3: Input/Output and Program Structure