While Loop in C++ Programming


The while loop is repeats a statement or block while its controlling expression is true.The condition can be any Boolean expression.

The body of the loop will be executed as long as the conditional expression 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 a simple implementation of the while loop in C++.

  • It starts by declaring two integer variables: i and n. The variable i is initialized to 1, while n is uninitialized.
  • The user is prompted to enter the value of n. The value entered by the user is read and stored in the variable n using the cin statement.
  • A while loop is used to print the numbers from 1 to n. The loop continues as long as the value of i is less than or equal to n.
  • Within the while loop, the value of i is printed using the cout statement. Then, the value of i is incremented by 1 using the i++ statement.
  • Once the loop condition becomes false, i.e., i becomes greater than n, the loop exits and the program terminates.

Source Code

/*
Looping Statement
    1.While
    2.do While
    3.for
    4.for each
*/
#include<iostream>
using namespace std;
int main()
{
     int i=1,n;
     cout<<"\nEnter The Limit : ";
     cin>>n;
     while(i<=n)
     {
         cout<<"\n"<<i;
         i++;
     }
     return 0;
}
 

Output

Enter The Limit : 10

1
2
3
4
5
6
7
8
9
10
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples