๐ 9. Loops
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 again9.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);
}| Part | When it runs |
|---|---|
| Initialization | once, before first test |
| Condition | before each possible iteration |
| Body | when condition is true |
| Iteration expression | after body, before next condition test |
9.5 while vs do-while vs for
| Loop | Best mental model | Can body run zero times? |
|---|---|---|
while | repeat while condition remains true | Yes |
do-while | perform action, then decide whether to repeat | No |
for | counter/control loop with initialization-test-update together | Yes |
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;
}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.
| Goal | Typical form |
|---|---|
| Indices of array with n elements | for (i = 0; i < n; i++) |
| Numbers 1 through n | for (i = 1; i <= n; i++) |
| n repetitions | Start 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
- 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
continuecannot skip essential progress. - Check bounds before indexing arrays.
9.15 Quick Revision
๐ 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.
๐ฌ Loops โ for Loop Execution
Follow the repeated control flow of a for loop:
initialization โ condition โ body โ update โ repeat or stop.
๐ฌ for Loop Execution Visualizer
The currently explained loop stage becomes active as you move through the controls.
๐ 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.
A for loop is commonly used when the iteration pattern or count can be expressed conveniently with initialization, condition and update.
A do-while loop executes the body before checking its condition, so the body runs at least once.
break immediately terminates the nearest enclosing loop or switch statement.
continue skips the remainder of the current iteration and proceeds with the loop's next iteration behavior.
i starts at 1, the condition permits values 1, 2 and 3, and i++ advances to the next value after each iteration.
The loop body executes for i = 1, 2, 3, 4 and 5, which is five iterations.
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.
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.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
if (i > 1)
printf(" ");
printf("%d", i);
}
return 0;
}
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.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
for (int i = n; i >= 1; i--)
{
if (i < n)
printf(" ");
printf("%d", i);
}
return 0;
}
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.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int n;
int first = 1;
scanf("%d", &n);
for (int i = 2; i <= n; i += 2)
{
if (!first)
printf(" ");
printf("%d", i);
first = 0;
}
return 0;
}
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.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int n;
int first = 1;
scanf("%d", &n);
for (int i = 1; i <= n; i += 2)
{
if (!first)
printf(" ");
printf("%d", i);
first = 0;
}
return 0;
}
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.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int n;
long long sum = 0;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
sum = sum + i;
}
printf("%lld", sum);
return 0;
}
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!.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int n;
unsigned long long fact = 1;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
fact = fact * i;
}
printf("%llu", fact);
return 0;
}
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.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
for (int i = 1; i <= 10; i++)
{
printf("%d x %d = %d", n, i, n * i);
if (i < 10)
printf("\n");
}
return 0;
}
Problem 8: Read an integer and count how many decimal digits it contains.
Input: One integer.
Output: Print the number of digits.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
long long n;
int count = 0;
scanf("%lld", &n);
if (n == 0)
{
count = 1;
}
else
{
if (n < 0)
n = -n;
while (n != 0)
{
n = n / 10;
count++;
}
}
printf("%d", count);
return 0;
}
Problem 9: Read an integer and reverse its decimal digits.
Input: One integer.
Output: Print the reversed integer.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
long long n;
long long reverse = 0;
int sign = 1;
scanf("%lld", &n);
if (n < 0)
{
sign = -1;
n = -n;
}
while (n != 0)
{
int digit = n % 10;
reverse = reverse * 10 + digit;
n = n / 10;
}
printf("%lld", reverse * sign);
return 0;
}
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".
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
long long n;
long long original;
long long temp;
long long reverse = 0;
scanf("%lld", &n);
original = n;
temp = n;
while (temp != 0)
{
int digit = temp % 10;
reverse = reverse * 10 + digit;
temp = temp / 10;
}
if (original == reverse)
printf("Palindrome");
else
printf("Not Palindrome");
return 0;
}
Problem 11: Read an integer and check whether it is prime.
Input: One integer N.
Output: Print "Prime" or "Not Prime".
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int n;
int isPrime = 1;
scanf("%d", &n);
if (n < 2)
{
isPrime = 0;
}
else
{
for (int i = 2; i * i <= n; i++)
{
if (n % i == 0)
{
isPrime = 0;
break;
}
}
}
if (isPrime)
printf("Prime");
else
printf("Not Prime");
return 0;
}
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.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int n;
int first = 1;
scanf("%d", &n);
for (int value = 2; value <= n; value++)
{
int isPrime = 1;
for (int d = 2; d * d <= value; d++)
{
if (value % d == 0)
{
isPrime = 0;
break;
}
}
if (isPrime)
{
if (!first)
printf(" ");
printf("%d", value);
first = 0;
}
}
return 0;
}
Problem 13: Read an integer and find the sum of its decimal digits.
Input: One integer.
Output: Print the sum of its digits.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
long long n;
int sum = 0;
scanf("%lld", &n);
if (n < 0)
n = -n;
while (n != 0)
{
sum = sum + (n % 10);
n = n / 10;
}
printf("%d", sum);
return 0;
}
Problem 14: Read an integer and find its largest decimal digit.
Input: One integer.
Output: Print the largest digit.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
long long n;
int largest = 0;
scanf("%lld", &n);
if (n < 0)
n = -n;
while (n != 0)
{
int digit = n % 10;
if (digit > largest)
largest = digit;
n = n / 10;
}
printf("%d", largest);
return 0;
}
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.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
long long n;
int even = 0;
int odd = 0;
scanf("%lld", &n);
if (n < 0)
n = -n;
if (n == 0)
{
even = 1;
}
else
{
while (n != 0)
{
int digit = n % 10;
if (digit % 2 == 0)
even++;
else
odd++;
n = n / 10;
}
}
printf("Even = %d\n", even);
printf("Odd = %d", odd);
return 0;
}
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.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
for (int row = 1; row <= 5; row++)
{
for (int col = 1; col <= row; col++)
{
if (col > 1)
printf(" ");
printf("*");
}
if (row < 5)
printf("\n");
}
return 0;
}
9.18 Key Takeaway
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.
๐ค Loops โ Interview Questions
๐ก 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 % 10andn = n / 10. - For prime checking, testing divisors only while
i * i <= nis 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.
โ๏ธ Loops โ Extra Practice Questions
- Print all multiples of 3 from 1 to N.
- Find the product of all odd numbers from 1 to N.
- Count how many times a given digit appears in an integer.
- Check whether a number is an Armstrong number.
- Print the first N terms of the Fibonacci sequence.
- Use nested loops to print a rectangular and an inverted-triangle star pattern.