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:
Repetitive tasks: Processing arrays, reading files, user input validation
Iteration: Performing calculations multiple times
Efficiency: Avoiding code duplication
Dynamic processing: Handling unknown amounts of data
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
}
return0;
}
// 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);
return0;
}
// 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.
#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);
return0;
}
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);
}
return0;
}
// 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);
return0;
}
// 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);
}
return0;
}
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.
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);
}
return0;
}
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;
}
return0;
}
// 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);
return0;
}
// Output: Original: 12345, Reversed: 54321
Assignment Questions
Easy Level:
Write a program to find the sum of all even numbers between 1 and 100.
Create a program that prints the multiplication table of any given number.
Write a program to count the number of digits in a given number.
Find the largest digit in a given number using loops.
Medium Level:
Write a program to check if a number is a palindrome.
Create a pattern printing program for various shapes (triangle, diamond, etc.).
Write a program to find the GCD (Greatest Common Divisor) of two numbers.
Calculate the power of a number without using built-in functions.
Hard Level:
Write a program to find all prime numbers between 1 and 1000 using the Sieve of Eratosthenes.
Create a program that converts decimal to binary using loops.
Write a menu-driven calculator with all basic operations using do-while loop.
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