Getting Started
Control Flow
Use if/else, switch, and loops to control program execution in C.
Conditional Statements
C provides if, else if, and else for conditional execution, plus the ternary operator.
Switch Statement
More efficient than long if/else chains when comparing one value against multiple integer or char constants.
Loops
for— known number of iterationswhile— unknown iterations, check beforedo-while— runs at least once, check after
Loop Control
break— exit the loop immediatelycontinue— skip to next iterationgoto— jump to a label (use sparingly)
Example
c
#include <stdio.h>
int main() {
/* if / else */
int score = 85;
if (score >= 90) {
printf("A\n");
} else if (score >= 80) {
printf("B\n");
} else {
printf("C or below\n");
}
/* Ternary operator */
int max = (score > 80) ? score : 80;
/* switch */
int day = 3;
switch (day) {
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
case 3: printf("Wednesday\n"); break;
default: printf("Other day\n"); break;
}
/* for loop */
for (int i = 0; i < 5; i++) {
printf("%d ", i);
}
printf("\n");
/* while loop */
int n = 1;
while (n <= 10) {
printf("%d ", n);
n++;
}
/* do-while */
int num;
do {
printf("Enter positive number: ");
scanf("%d", &num);
} while (num <= 0);
/* Nested loops with break */
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 2) break; /* break inner loop */
printf("(%d,%d) ", i, j);
}
}
return 0;
}Try it yourself — C