Welcome to The Coding College, where we simplify coding concepts for every learner! In this post, we’ll delve into practical examples of the while
loop in C programming, showcasing how this essential construct is used to handle repetitive tasks effectively.
What is a while
Loop?
The while
loop in C allows you to execute a block of code repeatedly as long as a specified condition evaluates to true. It is especially useful when the number of iterations is not known beforehand.
Syntax
while (condition) {
// Code to execute
}
- Condition: Evaluated before each iteration.
- Code Block: Executes only if the condition is true.
- Loop Exit: If the condition becomes false, the loop stops.
Example 1: Print Numbers from 1 to 10
#include <stdio.h>
int main() {
int i = 1;
while (i <= 10) {
printf("%d\n", i);
i++;
}
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
Explanation:
- Initialization:
i
is initialized to 1. - Condition: The loop runs as long as
i
is less than or equal to 10. - Update:
i++
incrementsi
in each iteration.
Example 2: Sum of Natural Numbers
#include <stdio.h>
int main() {
int n, sum = 0, i = 1;
printf("Enter a number: ");
scanf("%d", &n);
while (i <= n) {
sum += i; // Add i to sum
i++;
}
printf("Sum of first %d natural numbers is: %d\n", n, sum);
return 0;
}
Output:
Enter a number: 5
Sum of first 5 natural numbers is: 15
Explanation:
- The loop adds each number from
1
ton
tosum
.
Example 3: Reverse a Number
#include <stdio.h>
int main() {
int num, reverse = 0;
printf("Enter a number: ");
scanf("%d", &num);
while (num != 0) {
reverse = reverse * 10 + num % 10;
num /= 10;
}
printf("Reversed number is: %d\n", reverse);
return 0;
}
Output:
Enter a number: 1234
Reversed number is: 4321
Explanation:
- The loop extracts the last digit using
% 10
and shifts it to form the reversed number.
Example 4: Factorial of a Number
#include <stdio.h>
int main() {
int n, i = 1;
unsigned long long factorial = 1;
printf("Enter a number: ");
scanf("%d", &n);
while (i <= n) {
factorial *= i;
i++;
}
printf("Factorial of %d is: %llu\n", n, factorial);
return 0;
}
Output:
Enter a number: 5
Factorial of 5 is: 120
Explanation:
- The loop calculates the product of all integers from
1
ton
.
Example 5: Infinite Loop
#include <stdio.h>
int main() {
int i = 1;
while (1) { // Infinite loop
printf("%d\n", i);
i++;
if (i > 10) { // Exit condition
break;
}
}
return 0;
}
Output:
1
2
3
...
10
Explanation:
- The
break
statement is used to exit the infinite loop wheni
exceeds 10.
Use Cases for while
Loops
- User Input Validation: Ensure the input meets certain criteria.
- Menu-Driven Programs: Keep displaying a menu until the user chooses to exit.
- Processing Data: Perform operations on data until a condition is met.
Advanced Example: Fibonacci Sequence
#include <stdio.h>
int main() {
int n, t1 = 0, t2 = 1, nextTerm;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Sequence: ");
int i = 1;
while (i <= n) {
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
i++;
}
return 0;
}
Output:
Enter the number of terms: 5
Fibonacci Sequence: 0, 1, 1, 2, 3,
Best Practices
- Avoid Infinite Loops: Always ensure the loop has a valid termination condition.
- Keep It Simple: Don’t overcomplicate the logic inside the loop.
- Optimize Updates: Ensure variables in the condition are updated correctly within the loop.
Conclusion
The while
loop in C is a versatile tool that enables programmers to tackle a wide variety of tasks, from simple number printing to complex operations like reversing a number or generating a Fibonacci sequence. By mastering its use, you’ll elevate your coding efficiency and problem-solving skills.