๐Ÿ” 9. Loops

๐ŸŽ“ Concept-First Explanation

This lesson is organized in the same order a faculty member would normally teach it: meaning โ†’ purpose โ†’ syntax/model โ†’ internal working โ†’ examples โ†’ common confusion โ†’ safe use. The guided examples from the earlier lesson are preserved afterward for reinforcement.

9.1 What a Loop Really Is

A loop repeatedly executes a statement/block while a control rule allows repetition. Every useful loop has four conceptual parts: initialization, condition/test, body and progress/update. The syntax may place these parts in different locations.

Initialize state
     โ†“
Test condition โ”€โ”€falseโ”€โ”€โ†’ exit loop
     โ”‚ true
     โ†“
Execute body
     โ†“
Update/progress
     โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ†’ test again

9.2 while Loop โ€” Pre-Test Repetition

int i = 1;
while (i <= 5)
{
    printf("%d ", i);
    i++;
}

The condition is checked before each iteration. Therefore a while body can execute zero times if the condition is false initially.

9.3 do-while Loop โ€” Post-Test Repetition

int choice;
do
{
    printf("1. Continue  0. Exit: ");
    scanf("%d", &choice);
} while (choice != 0);

The body executes before the condition is tested, so it runs at least once. Notice the required semicolon after the closing while (...).

9.4 for Loop โ€” Put Control Mechanics Together

for (int i = 0; i < 5; i++)
{
    printf("%d ", i);
}
PartWhen it runs
Initializationonce, before first test
Conditionbefore each possible iteration
Bodywhen condition is true
Iteration expressionafter body, before next condition test

9.5 while vs do-while vs for

LoopBest mental modelCan body run zero times?
whilerepeat while condition remains trueYes
do-whileperform action, then decide whether to repeatNo
forcounter/control loop with initialization-test-update togetherYes

9.6 Counter-Controlled Loops

Use a counter when the number of repetitions is known or naturally indexed.

for (int i = 1; i <= n; i++)
{
    sum += i;
}
Invariant idea

Before each iteration, ask what must already be true. For example, before processing index i, sum may represent the total of earlier elements. This makes loops easier to reason about.

9.7 Sentinel-Controlled Loops

A sentinel is a special value or condition that signals termination rather than representing ordinary data.

int x;
while (scanf("%d", &x) == 1 && x != -1)
{
    /* process x */
}

The sentinel should be chosen so it cannot be mistaken for valid data, or the protocol must clearly distinguish it.

9.8 Nested Loops โ€” Understand Which Loop Repeats

for (int row = 0; row < 3; row++)
{
    for (int col = 0; col < 4; col++)
    {
        printf("(%d,%d) ", row, col);
    }
    putchar('\n');
}

For every one iteration of the outer loop, the inner loop normally runs through its full cycle. This produces 3 ร— 4 = 12 inner-body executions in the example.

9.9 break โ€” Exit the Nearest Loop

for (int i = 0; i < n; i++)
{
    if (a[i] == target)
    {
        position = i;
        break;
    }
}

break exits only the nearest enclosing loop or switch, not every surrounding loop automatically.

9.10 continue โ€” Skip the Rest of the Current Iteration

for (int i = 1; i <= 10; i++)
{
    if (i % 2 != 0)
        continue;
    printf("%d ", i);
}

In a for loop, the iteration expression still occurs before the next condition test. In a while loop, control jumps directly to the condition, so an update placed later in the body may be skipped.

int i = 0;
while (i < 5)
{
    if (i == 2)
        continue; /* BUG: i never changes here -> infinite loop */
    i++;
}

9.11 Off-by-One Errors

The difference between < and <= often decides whether a loop runs exactly the intended number of times.

GoalTypical form
Indices of array with n elementsfor (i = 0; i < n; i++)
Numbers 1 through nfor (i = 1; i <= n; i++)
n repetitionsStart at 0 and continue while i < n

9.12 Infinite Loops โ€” Intentional and Accidental

for (;;)
{
    /* service loop; must have an intentional exit mechanism if required */
}

An infinite loop is not automatically a bug; event loops and embedded firmware may intentionally run indefinitely. Accidental infinite loops usually come from a condition that never becomes false or a skipped update.

9.13 Overflow in Loop Counters and Accumulators

A loop can be logically correct but still fail if its counter or accumulator exceeds the representable range. Signed integer overflow is undefined behavior. Choose types and termination conditions with range in mind.

for (unsigned int i = 0; i < limit; i++)
{
    /* ensure limit and wraparound behavior cannot make termination incorrect */
}

9.14 A Loop-Debugging Checklist

Initial value? โ†’ condition? โ†’ body effect? โ†’ progress? โ†’ exact termination value?
  • Trace the first iteration.
  • Trace a middle iteration.
  • Trace the final successful iteration.
  • Trace the first failed condition.
  • Test zero/empty input when relevant.
  • Check that continue cannot skip essential progress.
  • Check bounds before indexing arrays.

9.15 Quick Revision

๐Ÿ“Œ for โ†’ Commonly used when iteration count is known.

๐Ÿ“Œ while โ†’ Condition checked before each iteration.

๐Ÿ“Œ do-while โ†’ Body executes before condition check.

๐Ÿ“Œ break โ†’ Exit loop.

๐Ÿ“Œ continue โ†’ Skip current iteration.

๐Ÿ“Œ Nested loops โ†’ Loop inside another loop.

๐Ÿ“Œ Always check initialization, condition and update.
INTERACTIVE LEARNING

๐ŸŽฌ Loops โ€” for Loop Execution

Follow the repeated control flow of a for loop: initialization โ†’ condition โ†’ body โ†’ update โ†’ repeat or stop.

PROGRAM TRACING

๐Ÿ”Ž Program Tracing โ€” Loops

Trace each iteration of a for loop and watch how i and sum change.

9.16 Quick MCQs

Select an answer first, then click Check Answer. A correct choice becomes green. If the answer is wrong, your choice becomes red and the correct option becomes green. The explanation appears below.

1. Which loop is commonly used when the number of iterations is known?
2. Which loop executes its body at least once?
3. Which keyword terminates the nearest enclosing loop?
4. Which keyword skips the remaining statements in the current loop iteration?
5. What is the output of for(int i = 1; i <= 3; i++) printf("%d ", i); ?
6. How many times does for(int i = 1; i <= 5; i++) execute its body?
PRACTICE

9.17 ๐ŸŽฏ Practice Problems

Loops become easy only through repeated practice. Use ๐Ÿ’ป Solve It Yourself first, open Hint only when needed, and use Show Program after attempting the problem.

๐Ÿ“ˆ Loops Practice Progress
Solved 0 / 16
Completed with Solution 0
Total Score 0 / 1600
Completion 0%
A problem counts as Solved when all test cases pass without opening the full solution. Problems completed after viewing the official solution are tracked separately.
1. Print Numbers from 1 to N

Problem 1: Read N and print all integers from 1 to N.

Input: One positive integer N.

Output: Print the numbers from 1 to N separated by spaces.

2. Print Numbers from N to 1

Problem 2: Read N and print all integers from N down to 1.

Input: One positive integer N.

Output: Print the numbers from N to 1 separated by spaces.

3. Print Even Numbers from 1 to N

Problem 3: Read N and print all even numbers from 1 to N.

Input: One positive integer N.

Output: Print all even values not greater than N.

4. Print Odd Numbers from 1 to N

Problem 4: Read N and print all odd numbers from 1 to N.

Input: One positive integer N.

Output: Print all odd values not greater than N.

5. Sum of First N Natural Numbers

Problem 5: Read N and find the sum of the natural numbers from 1 to N using a loop.

Input: One non-negative integer N.

Output: Print the sum.

6. Factorial of a Number

Problem 6: Read a non-negative integer N and calculate N! using a loop.

Input: One integer N in the range 0 to 20.

Output: Print N!.

7. Multiplication Table

Problem 7: Read a number and print its multiplication table from 1 to 10.

Input: One integer N.

Output: Print ten lines in the form N x i = result.

8. Count Digits in an Integer

Problem 8: Read an integer and count how many decimal digits it contains.

Input: One integer.

Output: Print the number of digits.

9. Reverse a Number

Problem 9: Read an integer and reverse its decimal digits.

Input: One integer.

Output: Print the reversed integer.

10. Palindrome Number

Problem 10: Read a non-negative integer and check whether it is a palindrome.

Input: One non-negative integer.

Output: Print "Palindrome" or "Not Palindrome".

11. Prime Number

Problem 11: Read an integer and check whether it is prime.

Input: One integer N.

Output: Print "Prime" or "Not Prime".

12. Print Prime Numbers from 1 to N

Problem 12: Read N and print every prime number from 1 to N.

Input: One integer N greater than or equal to 2.

Output: Print prime numbers separated by spaces.

13. Sum of Digits

Problem 13: Read an integer and find the sum of its decimal digits.

Input: One integer.

Output: Print the sum of its digits.

14. Largest Digit

Problem 14: Read an integer and find its largest decimal digit.

Input: One integer.

Output: Print the largest digit.

15. Count Even and Odd Digits

Problem 15: Read an integer and count how many of its decimal digits are even and how many are odd.

Input: One integer.

Output: Print the even-digit count and odd-digit count.

16. Print a Five-Row Star Pattern

Problem 16: Use nested loops to print the five-row triangular star pattern shown in the lesson.

Input: No input.

Output: Print 1 star on the first row, 2 on the second, up to 5 on the fifth row.

9.18 Key Takeaway

๐ŸŽฏ Every loop has three important ideas:

1. Initialization
Where does the loop start?

2. Condition
When should the loop continue?

3. Update
How does the loop variable change?

Remember:

Start โ†’ Check โ†’ Execute โ†’ Update โ†’ Repeat

Mastering loops is essential for solving programming problems involving numbers, digits, patterns, arrays and algorithms.
INTERVIEW PREPARATION

๐ŸŽค Loops โ€” Interview Questions

1. What is the main difference between for, while and do-while loops?
2. When is a for loop usually preferred?
3. What is an infinite loop?
4. What does break do inside a loop?
5. What does continue do inside a loop?
6. Why must loop initialization, condition and update be checked carefully?
7. What is a nested loop?
8. Why is i * i <= n often used in a prime-number test?
PLACEMENT TIPS

๐Ÿ’ก Loops โ€” Placement Tips

  • Before tracing any loop, write down the initial value, condition, body operation and update.
  • For output-prediction questions, record the loop variable value at the start of every iteration.
  • Watch carefully for < versus <=; this is a common source of off-by-one errors.
  • For digit problems, remember the standard pair: digit = n % 10 and n = n / 10.
  • For prime checking, testing divisors only while i * i <= n is much more efficient than checking all values up to n.
  • In nested loops, estimate the number of inner-loop executions because this often determines the program's time complexity.
EXTRA PRACTICE

โœ๏ธ Loops โ€” Extra Practice Questions

  1. Print all multiples of 3 from 1 to N.
  2. Find the product of all odd numbers from 1 to N.
  3. Count how many times a given digit appears in an integer.
  4. Check whether a number is an Armstrong number.
  5. Print the first N terms of the Fibonacci sequence.
  6. Use nested loops to print a rectangular and an inverted-triangle star pattern.
โ† Previous Topic: Decision Making Next Topic: Arrays โ†’