๐ Unit 4: Concepts of Loops
Welcome, coder! ๐
In this unit, weโll explore loops โ the magic that lets your program repeat tasks automatically, without writing the same code 100 times.
๐ค Why Use Loops?โ
Imagine printing numbers 1 to 100:
// Without loops (boring and impractical)
printf("1\n");
printf("2\n");
printf("3\n");
// ... 97 more times!
// With loops (much better)
for (int i = 1; i <= 100; i++) {
printf("%d\n", i);
}
Thatโs the power of loops! ๐
๐น Types of Loops in Cโ
| Loop Type | When to Use | Special Feature |
|---|---|---|
| while | Iterations unknown | Condition checked first |
| do-while | Must run at least once | Condition checked last |
| for | Iterations known | All parts in header |
๐ธ The while Loopโ
Repeats while the condition is true.
Syntaxโ
initialization;
while (condition) {
// repeat code
update;
}
Example: Print Numbersโ
int i = 1;
while (i <= 5) {
printf("Number: %d\n", i);
i++;
}
Example: Sum of Natural Numbersโ
int n, sum = 0, i = 1;
scanf("%d", &n);
while (i <= n) {
sum += i;
i++;
}
printf("Sum = %d\n", sum);
๐น The do-while Loopโ
Executes once before checking the condition.
Syntaxโ
do {
// code
update;
} while (condition);
Exampleโ
int y = 10;
do {
printf("This will print at least once!\n");
} while (y < 5);
Example: Menu Programโ
- Menu Code
- Why do-while?
int choice;
do {
printf("1. Add\n2. Subtract\n3. Exit\n");
scanf("%d", &choice);
// process choice
} while (choice != 3);
Even if the user picks "Exit" the first time,
the menu still shows once!
Thatโs why do-while is great for menus.
๐ธ The for Loopโ
Best when the number of iterations is known.
Syntaxโ
for (init; condition; update) {
// repeat code
}
Example: Multiplication Tableโ
int num;
scanf("%d", &num);
for (int i = 1; i <= 10; i++) {
printf("%d ร %d = %d\n", num, i, num * i);
}
Example: Factorialโ
int n; unsigned long long fact = 1;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
fact *= i;
}
printf("%d! = %llu\n", n, fact);
๐น Nested Loopsโ
Loops inside loops.
Example: Pattern Printingโ
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
Output:
*
* *
* * *
* * * *
* * * * *
๐ฎ Loop Control Statementsโ
breakโ
Exits loop immediately.
for (int i = 1; i <= 10; i++) {
if (i == 5) break;
printf("%d ", i);
}
continueโ
Skips current iteration.
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) continue;
printf("%d ", i);
}
โก Loop Variationsโ
Infinite Loopsโ
while (1) { /* runs forever */ }
for (;;) { /* also infinite */ }
Flexible for Loopโ
for (int i = 0, j = 10; i < 5; i++, j--) {
printf("i=%d, j=%d\n", i, j);
}
๐งช Practice Problemsโ
- โ Prime Checker (using for loop)
- โ Fibonacci Series
- โ Armstrong Number Checker
- โ Pattern Programs (hollow rectangle, diamond, Floydโs triangle)
๐ Quick Quizโ
Which loop always executes at least once?
- while
- do-while โ
- for
- None
๐ Thatโs it for Unit 4!
You can now repeat, automate, and generate patterns like a coding wizard ๐งโโ๏ธ.
Next up: Unit 5 โ Arrays ๐ฆ