While Loop in C with Example


A while loop in C is used to execute and repeat a block of statements based on a certain condition.

Also Read, C Program To Find Factorial of a Number with Example

Syntex:-
while()
{
<statement Block>
}

  • while is the relational or logical expression that will have the value of true or false.
  • When this statement is executed, the computer will evaluate the value of the condition.
  • If the evaluated value is true, then the block of statement is executed and is repeated until the value of the condition is false.

There must be a statement written inside the statement block to change the value of the condition, the loop will be in the infinite state.

Print natural numbers from 1 to n using while loop in C language

Complete Code:-

#include <stdio.h>
main()
{
    int i, n;
    printf("Enter the value to n:");
    scanf("%d",&n);
    //while loop to print the numbers
    while(i<=n)
    {
        i++;
        printf("\n %d",i);
    }
}

After running the above program, the user has to enter the nth value and press the ENTER key.

Enter the value to n: 5

Then the program will be executed and the result will be displayed as shown below

1
2
3
4
5
6
Process returned 0 (0x0) execution time : 3.767 s
Press any key to continue.

Conclusion:- I hope this tutorial will help you to understand the concept of while loop structure. If there is any doubt then please leave a comment below


Leave a Comment