C While Loop Examples

1. Printing Numbers from 1 to 10

#include <stdio.h>

int main() {
int i = 1;

while (i <= 10) {
printf("%d ", i);
i++;
}

return 0;
}

Output:

1 2 3 4 5 6 7 8 9 10

2. Sum of First N Natural Numbers

#include <stdio.h>

int main() {
int n, i = 1, sum = 0;

printf("Enter a number: ");
scanf("%d", &n);

while (i <= n) {
sum += i;
i++;
}

printf("Sum = %d\n", sum);
return 0;
}

Sample Input/Output:

Enter a number: 5
Sum = 15

3. Printing Even Numbers from 2 to 20

#include <stdio.h>

int main() {
int i = 2;

while (i <= 20) {
printf("%d ", i);
i += 2;
}

return 0;
}

Output:

2 4 6 8 10 12 14 16 18 20

4. Factorial of a Number

#include <stdio.h>

int main() {
int n, i = 1;
long factorial = 1;

printf("Enter a number: ");
scanf("%d", &n);

while (i <= n) {
factorial *= i;
i++;
}

printf("Factorial of %d = %ld\n", n, factorial);
return 0;
}

Sample Input/Output:

Enter a number: 5
Factorial of 5 = 120

5. Reading Numbers Until Zero is Entered

#include <stdio.h>

int main() {
int num;

printf("Enter numbers (0 to stop):\n");
scanf("%d", &num);

while (num != 0) {
printf("You entered: %d\n", num);
scanf("%d", &num);
}

printf("Loop ended.\n");
return 0;
}

Sample Input/Output:

Enter numbers (0 to stop):
5
You entered: 5
3
You entered: 3
0
Loop ended.

6. Multiplication Table of a Number

#include <stdio.h>

int main() {
int n, i = 1;

printf("Enter a number: ");
scanf("%d", &n);

while (i <= 10) {
printf("%d x %d = %d\n", n, i, n * i);
i++;
}

return 0;
}

Sample Input/Output:

Enter a number: 7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
...
7 x 10 = 70

Key Points from Examples

  1. while loop is used when number of iterations is not fixed or depends on a condition.

  2. Always update loop variables to prevent infinite loops.

  3. Can be used for counting, summing, input validation, and repetitive tasks.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *