C ProgrammingUnit 513 min read
Loops & Nested Loops: Types, Patterns, and Real-World Applications
Unit 5 of C Programming covers looping constructs (for, while, do-while), nested loops, and their applications in pattern generation, prime number checks, and iterative problem-solving. Learn how loops automate repetitive tasks, optimize code, and solve complex patterns—with real-world examples from eSewa, Daraz, and b
TAKEAWAYS:
- Three loop types:
for(count-controlled),while(condition-controlled),do-while(post-test) differ in initialization, condition, and update placement. - Nested loops enable multi-dimensional tasks (e.g., matrix traversal, pattern printing) by embedding loops inside loops.
- Pattern generation uses nested loops to print structured outputs (e.g., pyramids, number sequences) by controlling row/column logic.
- Prime checks leverage loops to test divisibility iteratively, optimizing with
sqrt(n)for efficiency. - Real-world ties: Loops power transaction validation (e.g., eSewa’s payment retries), inventory systems (Daraz’s stock checks), and loan calculations (bank interest).
- Exam focus: Write correct loop conditions, avoid infinite loops, and trace variable changes step-by-step for full marks.
1. Introduction to Loops
Loops in C repeat code blocks until a condition is met, reducing redundancy. They are essential for:
- Processing arrays/lists.
- Generating patterns.
- Validating inputs (e.g., retries in eSewa).
- Simulating real-world cycles (e.g., Daraz’s order fulfillment).
Types of Loops
graph LR
A["Loops in C"] --> B["for"]
A --> C["while"]
A --> D["do-while"]
B -->|"count-controlled"| E["Initialization; Condition; Update"]
C -->|"condition-controlled"| F["Test before execution"]
D -->|"post-test"| G["Execute then test"]2. for Loop: Count-Controlled Repetition
Syntax:
for (initialization; condition; update) {
// Code to repeat
}
How it works:
- Initialization: Runs once (e.g.,
int i=0). - Condition: Checked before each iteration (e.g.,
i<5). - Update: Executed after each iteration (e.g.,
i++).
Example: Print Numbers 1 to 5
for (int i=1; i<=5; i++) {
printf("%d ", i);
}
Trace Table:
| Iteration | i (init) |
Condition (i<=5) |
Output | i (update) |
|---|---|---|---|---|
| 1 | 1 | True | 1 | 2 |
| 2 | 2 | True | 2 | 3 |
| ... | ... | ... | ... | ... |
| 5 | 5 | True | 5 | 6 |
| 6 | 6 | False | Exit | - |
Visualization: Real-World Tie:
- eSewa’s Payment Retry Logic:
Usesfor (int attempts=0; attempts<3; attempts++) { if (processPayment()) break; }forto retry failed transactions up to 3 times.
3. while Loop: Condition-Controlled Repetition
Syntax:
while (condition) {
// Code to repeat
}
Key Points:
- Test before execution: May never run if
conditionisfalseinitially. - Infinite loop risk: If
conditionnever becomesfalse(e.g., missingi++).
Example: Sum of Digits
int num = 1234, sum = 0;
while (num != 0) {
sum += num % 10; // Extract last digit
num /= 10; // Remove last digit
}
printf("Sum = %d", sum); // Output: 10
Trace Table:
| Iteration | num |
sum |
num % 10 |
num /= 10 |
Condition (num != 0) |
|---|---|---|---|---|---|
| 1 | 1234 | 0 | 4 | 123 | True |
| 2 | 123 | 4 | 3 | 12 | True |
| 3 | 12 | 7 | 2 | 1 | True |
| 4 | 1 | 9 | 1 | 0 | True |
| 5 | 0 | 10 | - | - | False |
Visualization:
Real-World Tie:
- Daraz’s Order Fulfillment Queue:
Useswhile (ordersInQueue > 0) { processOrder(); ordersInQueue--; }whileto handle orders until the queue is empty.
4. do-while Loop: Post-Test Repetition
Syntax:
do {
// Code to repeat
} while (condition);
Key Difference:
- Guarantees at least one execution (test happens after).
- Useful for menus or input validation.
Example: Simple Menu
int choice;
do {
printf("\n1. Deposit\n2. Withdraw\n3. Exit\n");
scanf("%d", &choice);
// Process choice...
} while (choice != 3);
Trace Table:
| Iteration | choice |
Action | Condition (choice != 3) |
|---|---|---|---|
| 1 | 1 | Deposit | True |
| 2 | 2 | Withdraw | True |
| 3 | 3 | Exit | False |
Visualization:
flowchart TD
A["Start"] --> B["Show Menu"]
B --> C{"choice == 3?"}
C -->|"No"| D["Process Choice"]
D --> B
C -->|"Yes"| E["Exit"]Real-World Tie:
- Ncell’s Top-Up Retry:
Usesdo { if (validatePin()) break; printf("Invalid PIN. Retry.\n"); } while (1); // Infinite until validdo-whileto ensure PIN validation runs at least once.
5. Nested Loops: Multi-Layered Repetition
Definition: A loop inside another loop. The inner loop completes all iterations for each outer loop iteration.
Example: Multiplication Table
for (int i=1; i<=3; i++) { // Outer loop (rows)
for (int j=1; j<=3; j++) { // Inner loop (columns)
printf("%d ", i*j);
}
printf("\n");
}
Output:
1 2 3
2 4 6
3 6 9
Trace Table:
Outer i |
Inner j |
i*j |
Output (per row) |
|---|---|---|---|
| 1 | 1, 2, 3 | 1, 2, 3 | 1 2 3 |
| 2 | 1, 2, 3 | 2, 4, 6 | 2 4 6 |
| 3 | 1, 2, 3 | 3, 6, 9 | 3 6 9 |
Visualization:
Real-World Tie:
- Bank Loan Interest Calculation:
Nested loops could extend this to calculate monthly interest within each year.for (int year=1; year<=5; year++) { // Outer: years float interest = principal * rate; principal += interest; printf("Year %d: %.2f\n", year, interest); }
6. Pattern Generation with Nested Loops
Common Patterns:
Right-Angled Triangle:
for (int i=1; i<=4; i++) { for (int j=1; j<=i; j++) { printf("* "); } printf("\n"); }Output:
* * * * * * * * * *Pyramid:
for (int i=1; i<=5; i++) { for (int j=1; j<=5-i; j++) printf(" "); for (int j=1; j<=2*i-1; j++) printf("*"); printf("\n"); }Output:
* *** ***** *******
Exam Tip: For pattern questions, identify the logic for rows and columns separately. Use printf(" ") for spaces and printf("*") for stars.
7. Prime Number Check with Loops
Algorithm:
- Test divisibility from
2tosqrt(n). - If any divisor divides
n, it’s not prime.
#include <math.h>
int isPrime(int n) {
if (n <= 1) return 0;
for (int i=2; i<=sqrt(n); i++) {
if (n % i == 0) return 0;
}
return 1;
}
Trace for n=17:
i |
sqrt(17) (~4.1) |
17 % i |
Condition (i <= 4) |
Prime? |
|---|---|---|---|---|
| 2 | 4.1 | 1 | True | Check |
| 3 | 4.1 | 2 | True | Check |
| 4 | 4.1 | 1 | True | Check |
| 5 | 4.1 | - | False | Exit |
Output: 1 (prime).
Real-World Tie:
- NEPSE’s Stock Validity Check:
Uses prime checks to validate unique stock identifiers.if (!isPrime(stockCode)) { printf("Invalid stock code!\n"); }
8. Loop Control Statements
| Statement | Purpose | Example |
|---|---|---|
break |
Exit loop immediately | if (x > 10) break; |
continue |
Skip current iteration | if (x % 2 == 0) continue; |
goto |
Jump to labeled line (avoid) | goto error; |
Example with break:
for (int i=1; i<=5; i++) {
if (i == 3) break; // Exit at i=3
printf("%d ", i);
}
// Output: 1 2
9. Common Pitfalls & How to Avoid Them
| Pitfall | Cause | Fix |
|---|---|---|
| Infinite loop | Missing update in for |
Ensure i++ or num-- exists |
| Off-by-one error | Incorrect condition (i<=n vs i<n) |
Test edge cases (e.g., n=1) |
| Uninitialized variable | Using i without int i=0 |
Always initialize loop variables |
| Logic errors in patterns | Misaligned spaces/stars | Draw the pattern manually first |
10. Comparison of Loop Types
| Feature | for |
while |
do-while |
|---|---|---|---|
| Use Case | Count-controlled | Condition-controlled | Post-test |
| Initialization | Inside loop header | Outside | Outside |
| Test Timing | Before execution | Before execution | After execution |
| Guaranteed Run | No | No | Yes |
| Example | for (i=0; i<5; i++) |
while (x>0) |
do { ... } while (x>0); |
11. Exam Tip: How to Score Full Marks
Loop Structure:
- Always include initialization, condition, and update (for
for). - For
while/do-while, clearly state the termination condition.
- Always include initialization, condition, and update (for
Pattern Questions:
- Break down rows/columns: Ask, “How many stars/spaces per row?”
- Use nested loops: Outer loop for rows, inner for columns.
- Example Trace: Show the first 2–3 iterations in your answer.
Prime Checks:
- Optimize: Test up to
sqrt(n), notn/2. - Edge Cases: Handle
n <= 1separately.
- Optimize: Test up to
Avoid Common Mistakes:
- Infinite loops: Ensure the loop variable changes.
- Off-by-one: Test with
n=1andn=2.
Real-World Connection:
- Link loops to transaction retries (eSewa), inventory checks (Daraz), or interest calculations (banks).
- Example: “This
forloop retries a failed payment like eSewa does.”
12. Practice Questions (Exam-Style)
Write a program to print:
1 1 2 1 2 3 1 2 3 4Hint: Use nested loops with
printf("%d ", j)inside the inner loop.Check if a number is a palindrome (e.g., 121) using loops. Hint: Reverse the number and compare.
Calculate the sum of even numbers from 1 to
nusing awhileloop.Print the following pattern:
10101 0101 101 01 1Hint: Use a counter to alternate
1and0.
13. Model Answer: Prime Number Check
Question: Write a C program to check if a number is prime or composite.
#include <stdio.h>
#include <math.h>
int main() {
int n, is_prime = 1;
printf("Enter a number: ");
scanf("%d", &n);
if (n <= 1) {
is_prime = 0;
} else {
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
is_prime = 0;
break;
}
}
}
if (is_prime) {
printf("%d is a prime number.\n", n);
} else {
printf("%d is a composite number.\n", n);
}
return 0;
}
Trace for n=17:
i |
sqrt(17) |
17 % i |
is_prime |
Condition (i <= 4) |
|---|---|---|---|---|
| 2 | 4.1 | 1 | 1 | True |
| 3 | 4.1 | 2 | 1 | True |
| 4 | 4.1 | 1 | 1 | True |
| 5 | 4.1 | - | 1 | False |
Output: 17 is a prime number.
14. In the Real World
eSewa’s Payment Retry System:
- Loop Type:
fororwhile - How: Retries failed transactions up to 3 times before notifying the user.
- Code Snippet:
for (int retry=0; retry<3; retry++) { if (processPayment()) break; printf("Retry %d...\n", retry+1); }
- Loop Type:
Daraz’s Inventory Management:
- Loop Type: Nested
forloops - How: Checks stock levels across all product categories daily.
- Example:
for (int category=0; category<10; category++) { for (int product=0; product<100; product++) { if (stock[category][product] < 5) reorder(); } }
- Loop Type: Nested
Ncell’s Top-Up Validation:
- Loop Type:
do-while - How: Ensures the user enters a valid PIN before processing.
- Example:
do { printf("Enter PIN: "); scanf("%d", &pin); } while (!validatePIN(pin));
- Loop Type:
Bank Loan Interest Calculation:
- Loop Type: Nested loops
- How: Calculates monthly interest for each year of the loan term.
- Example:
for (int year=0; year<loanTerm; year++) { for (int month=0; month<12; month++) { monthlyInterest = principal * rate / 12; principal += monthlyInterest; } }
15. Summary Checklist for Exams
- Can you differentiate
for,while, anddo-whileloops? - Can you write nested loops to generate patterns?
- Can you trace a loop’s execution step-by-step?
- Can you optimize a prime check using
sqrt(n)? - Can you connect loops to real-world systems (e.g., eSewa, Daraz)?
Based on the TU BCA syllabus for C Programming (CACS151), unit 5.
Discussion
Loading…