In C programming, the while and do-while loops are used to execute a block of code repeatedly as long as a specified condition is true.
While loop:
- In a while loop, the condition is checked before each iteration.
- If the condition is true, the code block inside the loop is executed.
- If the condition becomes false, the loop is exited, and the program continues with the next statement after the loop.
Basic syntax of a while loop in C:
C
while (condition) {
// code to be executed
}
- The condition is a Boolean expression that determines whether the loop should continue or not.
- If the condition is initially false, the code inside the loop will never be executed.
Example:
C
#include <stdio.h>
int main() {
int count = 0;
while (count < 5) {
printf("Count: %d\n", count);
count++;
}
return 0;
}
Output:
Output
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
Practice problems on While loop in C:
Problem 1: Sum of Natural Numbers
Write a program that calculates the sum of the first n natural numbers using a while loop. The value of n is provided by the user.
C
#include <stdio.h>
int main() {
int n, sum = 0, i = 1;
printf("Enter the value of n: ");
scanf("%d", &n);
while (i <= n) {
sum += i;
i++;
}
printf("Sum of the first %d natural numbers is %d\n", n, sum);
return 0;
}
Explanation:
- The program takes input from the user for the value of n.
- Then, it initializes two variables sum and i to 0 and 1 respectively.
- The while loop continues until i is less than or equal to n.
- In each iteration, i is added to the sum, and i is incremented by 1.
- Finally, the sum is printed.
Output:
Output
Enter the value of n: 5
Sum of the first 5 natural numbers is 15
Problem 2: Factorial Calculation
Write a program to calculate the factorial of a given number using a while loop. The value of the number is provided by the user.
C
#include <stdio.h>
int main() {
int n, fact = 1, i = 1;
printf("Enter a positive integer: ");
scanf("%d", &n);
while (i <= n) {
fact *= i;
i++;
}
printf("Factorial of %d is %d\n", n, fact);
return 0;
}
Explanation:
- The program takes input from the user for a positive integer n.
- It initializes two variables fact and i to 1.
- The while loop continues until i is less than or equal to n.
- In each iteration, i is multiplied with fact, and i is incremented by 1.
- Finally, the factorial is printed.
Output:
Output
Enter a positive integer: 5
Factorial of 5 is 120