The while loop can be used to calculate the sum of a series of numbers. In this program, the variable n starts from 1 and continues up to 10. During each iteration, the current value of n is added to the variable total. After the loop ends, the total sum of the first 10 numbers is displayed.
How It Works?
n with 1 and total with 0.while loop checks whether n <= 10.n.n to total.n by 1.#include <stdio.h> #include <conio.h> main() { int n = 1, total = 0; clrscr(); while(n <= 10) { printf("\n%d", n); total = total + n; n = n + 1; } printf("\nTotal : %d", total); getch(); }
while loop to print the numbers from 1 to 10 and calculate their product.while loop to multiply a series of numbers using a product variable.n with 1 and product with 1. Use the condition n <= 10. Multiply product by n inside the loop, then increase n by 1.#include <stdio.h> #include <conio.h> main() { long int product = 1; int n = 1; clrscr(); while(n <= 10) { printf("\n%d", n); product = product * n; n = n + 1; } printf("\nProduct : %ld", product); getch(); }
product to 1 and n to 1. The while loop prints the numbers from 1 to 10. During each iteration, the current value of n is multiplied with product, and then n is increased by 1. After the loop ends, the program displays the product of the numbers from 1 to 10, which is 3628800.