Skip to main content

๐Ÿ”„ 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 TypeWhen to UseSpecial Feature
whileIterations unknownCondition checked first
do-whileMust run at least onceCondition checked last
forIterations knownAll 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โ€‹

int choice;
do {
printf("1. Add\n2. Subtract\n3. Exit\n");
scanf("%d", &choice);
// process choice
} while (choice != 3);

๐Ÿ”ธ 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โ€‹

  1. โœ… Prime Checker (using for loop)
  2. โœ… Fibonacci Series
  3. โœ… Armstrong Number Checker
  4. โœ… 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 ๐Ÿ“ฆ