Understanding the While Loop in C Programming


While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. It is an entry-controlled loop. The body of the loop will be executed as long as the condition is true. When condition becomes false, control passes to the next line of code immediately following the loop.

  • If the condition to true, the code inside the while loop is executed.
  • The condition is evaluated again.
  • This process continues until the condition is false.
  • When the condition to false, the loop stops.

Syntax:
   while ( Condition )
   {
       // body of loop ;
       // Increment (or) Decrement ;
   }

The program is written in C and it demonstrates the use of the while loop.

  • The program starts with the inclusion of the header file "stdio.h" which contains the function printf() used in the program.
  • The program declares an integer variable "i" and initializes it with 1. Then it prompts the user to enter a limit using the scanf() function and stores the value in the variable "n".
  • The program then enters a while loop, which will execute as long as the condition i<=n is true. Inside the while loop, the program uses the printf() function to print the value of the variable "i". It then increments the value of "i" by 1 using the increment operator (++).
  • The while loop continues to execute until the value of "i" becomes greater than "n". Once the condition becomes false, the program exits the while loop and continues to execute the next statement after the while loop.
  • Finally, the program returns 0 to indicate successful execution.

In this program, the while loop will print all the numbers from 1 to n (inclusive) that the user entered. So, the program will print 1, 2, 3 ... n numbers.

Source Code

/*
    Looping Statement
 
        1.Entry Check Loop
            While
            For
        2.Exit Check Loop
            do while
 
while(condition)
{
    ----
    ----
    ----
}
*/
#include<stdio.h>
int main()
{
    int i=1,n;
    printf("\nEnter The Limit : ");
    scanf("%d",&n);
    while(i<=n)
    {
        printf("\n%d",i);
        i++;
    }
    return 0;
}
 
To download raw file Click Here

Output

Enter The Limit : 10

1
2
3
4
5
6
7
8
9
10

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C