C language loops | while loop

More examples of while loop

While Set 1:Q1-Q10    While Set 2:Q11-Q20    While Set 3:Q21-Q30

For Loop      While Loop      Do while Loop

While loop

Syntax :

while(condition)
{
statements;
statements;
statements;
}

* While loop is an entry control loop.
* In while loop the condition is checked first and then the statements of the loop are executed.
* In while loop if the specified condition is true then only the control enters the loop otherwise not.

While loop examples:

Example:1
Write a C program to print numbers from 1 to 10
Sol:

#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

Example:2
Write a C program to print numbers from 1 to 10 in reverse order
Sol:

#include<stdio.h>
 int main()
 {
     int i=10;
     while(i>=1)
     {
         printf("%d\n",i);
         i--;
     }
 return 0;
 }

Output:

10
9
8
7
6
5
4
3
2
1

Example:3
Write a C program to print all even numbers from upto 20
Sol:

#include<stdio.h>
 int main()
 {
     int i=2;
     while(i<=20)
     {
         printf("%d\n",i);
         i=i+2;
     }
 return 0;
 }

Output:

2
4
6
8
10
12
14
16
18
20

Example:4
Write a C program to print alll even numbers from upto 20 in reverse order
Sol:

#include<stdio.h>
 int main()
 {
     int i=20;
     while(i>=2)
     {
         printf("%d\n",i);
         i=i-2;
     }
 return 0;
 }

Output:

20
18
16
14
12
10
8
6
4
2

Example:5
Write a C program to print alll odd numbers from upto 25
Sol:

#include<stdio.h>
 int main()
 {
     int i=1;
     while(i<=25)
     {
         printf("%d\n",i);
         i=i+2;
     }
 return 0;
 }

Output:

1
3
5
7
9
11
13
15
17
19
21
23
25

For Loop      While Loop      Do while Loop

C Language Programming Tutorial

C Language Tutorial Home     Introduction to C Language     Tokens     If Condition      goto statement and Labelname     Switch Statements     For loop     While Loop     Do while loop     break and continue     Functions     Recursion     Inbuild Functions     Storage Classes     Preprocessor     Arrays     Pointers     Structures and Unions     File Handling     Projects