C Programming: Loops

while, do-while, and for loops
Lecture 9 | BTech First Semester
Dr. Mohsin Dar | Cloud & Software Operations Cluster | SOCS | UPES

What are Loops?

Loops are control structures that allow us to execute a block of code repeatedly based on a given condition. They are essential for:

Key Concept: Every loop has three essential components:
1. Initialization - Setting up the loop variable
2. Condition - Test that determines if loop continues
3. Update - Modifying the loop variable

1. While Loop

The while loop is an entry-controlled loop that executes as long as the condition is true.

Syntax:

while (condition) { // statements to be executed }

Flowchart:

Start
Check Condition
Execute Body

Example 1: Printing Numbers 1 to 5

#include <stdio.h> int main() { int i = 1; while (i <= 5) { printf("%d ", i); i++; // increment i } return 0; } // Output: 1 2 3 4 5

Example 2: Sum of First N Natural Numbers

#include <stdio.h> int main() { int n = 10, sum = 0, i = 1; while (i <= n) { sum += i; i++; } printf("Sum = %d", sum); return 0; } // Output: Sum = 55

2. Do-While Loop

The do-while loop is an exit-controlled loop that executes at least once, then continues while the condition is true.

Syntax:

do { // statements to be executed } while (condition);
Key Difference: The do-while loop guarantees at least one execution of the loop body, even if the condition is initially false.

Example 1: Menu-Driven Program

#include <stdio.h> int main() { int choice; do { printf("Menu:\n1. Add\n2. Subtract\n3. Exit\n"); printf("Enter choice: "); scanf("%d", &choice); switch(choice) { case 1: printf("Addition selected\n"); break; case 2: printf("Subtraction selected\n"); break; case 3: printf("Goodbye!\n"); break; default: printf("Invalid choice!\n"); } } while (choice != 3); return 0; }

Example 2: Input Validation

#include <stdio.h> int main() { int num; do { printf("Enter a positive number: "); scanf("%d", &num); if (num <= 0) { printf("Invalid! Please try again.\n"); } } while (num <= 0); printf("You entered: %d\n", num); return 0; }

3. For Loop

The for loop is the most commonly used loop when the number of iterations is known. It combines initialization, condition, and update in one line.

Syntax:

for (initialization; condition; update) { // statements to be executed }
Initialize
Check Condition
Execute Body
Update

Example 1: Basic For Loop

#include <stdio.h> int main() { for (int i = 1; i <= 5; i++) { printf("%d ", i); } return 0; } // Output: 1 2 3 4 5

Example 2: Factorial Calculation

#include <stdio.h> int main() { int n = 5, factorial = 1; for (int i = 1; i <= n; i++) { factorial *= i; } printf("Factorial of %d = %d", n, factorial); return 0; } // Output: Factorial of 5 = 120

Example 3: Multiplication Table

#include <stdio.h> int main() { int num = 7; printf("Multiplication table of %d:\n", num); for (int i = 1; i <= 10; i++) { printf("%d x %d = %d\n", num, i, num * i); } return 0; }

Loop Comparison

Feature While Loop Do-While Loop For Loop
Control Type Entry-controlled Exit-controlled Entry-controlled
Minimum Executions 0 (if condition is false) 1 (always executes once) 0 (if condition is false)
Best Used When Number of iterations unknown Must execute at least once Number of iterations known
Syntax Complexity Simple Simple Compact (all in one line)
Common Usage Reading files, user input Menu systems, validation Arrays, counting, iteration

Nested Loops

A loop inside another loop is called a nested loop. The inner loop completes all its iterations for each iteration of the outer loop.

Example 1: Pattern Printing

#include <stdio.h> int main() { for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { printf("* "); } printf("\n"); } return 0; } /* Output: * * * * * * * * * * * * * * * */

Example 2: Matrix Multiplication (2x2)

#include <stdio.h> int main() { int a[2][2] = {{1, 2}, {3, 4}}; int b[2][2] = {{5, 6}, {7, 8}}; int c[2][2] = {0}; // Matrix multiplication for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 2; k++) { c[i][j] += a[i][k] * b[k][j]; } } } printf("Result matrix:\n"); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { printf("%d ", c[i][j]); } printf("\n"); } return 0; }

Loop Control Statements

C provides statements to alter the normal flow of loops:

1. Break Statement

Terminates the loop immediately and transfers control to the statement after the loop.

#include <stdio.h> int main() { for (int i = 1; i <= 10; i++) { if (i == 6) { break; // Exit loop when i equals 6 } printf("%d ", i); } return 0; } // Output: 1 2 3 4 5

2. Continue Statement

Skips the rest of the current iteration and moves to the next iteration.

#include <stdio.h> int main() { for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { continue; // Skip even numbers } printf("%d ", i); } return 0; } // Output: 1 3 5 7 9

Interactive Demo

Loop Visualization

Click the buttons below to see different loop examples in action:

Click any button above to see the loop output!

Common Mistakes and Best Practices

❌ Common Mistakes:

1. Infinite Loops:

// Wrong - i is never updated int i = 1; while (i <= 5) { printf("%d ", i); // Missing: i++; }

2. Off-by-One Errors:

// Wrong - should be i < 5 or i <= 4 for (int i = 0; i <= 5; i++) { array[i] = i; // May cause array overflow }

3. Semicolon After For Statement:

// Wrong - semicolon creates empty loop body for (int i = 0; i < 5; i++); { printf("%d ", i); }

✅ Best Practices:

  • Always ensure loop termination: Make sure the condition will eventually become false
  • Initialize variables properly: Set initial values before using in loops
  • Use meaningful variable names: Use descriptive names like 'count' instead of 'i' when appropriate
  • Keep loop body simple: Complex operations should be in separate functions
  • Indent properly: Use consistent indentation for readability
  • Choose the right loop: Use for when iterations are known, while for unknown iterations

Practice Problems

Problem 1: Prime Number Checker

Write a program to check if a number is prime using loops.

#include <stdio.h> int main() { int num = 29, isPrime = 1; if (num <= 1) { isPrime = 0; } else { for (int i = 2; i * i <= num; i++) { if (num % i == 0) { isPrime = 0; break; } } } if (isPrime) { printf("%d is prime", num); } else { printf("%d is not prime", num); } return 0; }

Problem 2: Fibonacci Series

Generate the first n terms of Fibonacci series.

#include <stdio.h> int main() { int n = 10, first = 0, second = 1, next; printf("Fibonacci Series: "); if (n >= 1) printf("%d ", first); if (n >= 2) printf("%d ", second); for (int i = 3; i <= n; i++) { next = first + second; printf("%d ", next); first = second; second = next; } return 0; } // Output: Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

Problem 3: Reverse a Number

Reverse the digits of a given number.

#include <stdio.h> int main() { int num = 12345, reversed = 0, remainder; int original = num; while (num != 0) { remainder = num % 10; reversed = reversed * 10 + remainder; num /= 10; } printf("Original: %d\n", original); printf("Reversed: %d\n", reversed); return 0; } // Output: Original: 12345, Reversed: 54321

Assignment Questions

Easy Level:

  1. Write a program to find the sum of all even numbers between 1 and 100.
  2. Create a program that prints the multiplication table of any given number.
  3. Write a program to count the number of digits in a given number.
  4. Find the largest digit in a given number using loops.

Medium Level:

  1. Write a program to check if a number is a palindrome.
  2. Create a pattern printing program for various shapes (triangle, diamond, etc.).
  3. Write a program to find the GCD (Greatest Common Divisor) of two numbers.
  4. Calculate the power of a number without using built-in functions.

Hard Level:

  1. Write a program to find all prime numbers between 1 and 1000 using the Sieve of Eratosthenes.
  2. Create a program that converts decimal to binary using loops.
  3. Write a menu-driven calculator with all basic operations using do-while loop.
  4. Implement a simple number guessing game with limited attempts.

Summary

Key Takeaways:

  • While Loop: Entry-controlled, best for unknown iterations
  • Do-While Loop: Exit-controlled, guarantees at least one execution
  • For Loop: Most compact, ideal for known iterations
  • Nested Loops: Loop inside another loop, useful for 2D operations
  • Loop Control: Use break and continue for flow control

Next Lecture Preview:

Arrays in C Programming

We'll explore how to store and manipulate multiple values using arrays, and see how loops make array operations efficient and elegant.

Thank You!

Questions & Discussion

Dr. Mohsin Dar | Cloud & Software Operations Cluster | SOCS | UPES

Office Hours: Available for doubts and additional practice problems