While Loop in C++

C++ While loop

While loop is an entry controlled loop. The condition is evaluated and if it is true then body of loop is executed. After execution of body the condition is once again evaluated and if is true body is executed once again. This goes on until test condition becomes false.

Syntax of while loop:

While (condition)


Program 1.1 :

Program to find the sum of n natural number?

#include<iostream.h>      // including header file
void main()                       // creating main function
int i=1, n,sum = 0;
cout<<”Enter the number”<<endl;
cin>>n>>endl;                // taking user input
while (i<=n)
{                                     // body of while begins
sum = sum + i;  
i = i+1;
}                                // body of while ends
cout<<”Sum of first”<<n<<”natural number is”<<sum;

Enter a number
Sum of first 5 natural number is 15

Program 1.2 :

Program to find the sum of positive number & if user input negative number then loops ends. Negative number will not be added .

# include<iostream.h> // including header file
int  main()                     // creating main function
int  num;
int sum = 0;
cout<<”Enter a number”;
while (num>=0)
{                                 // body of while loop
sum += number;
cout<<”Enter a number”;

cout<<”The sum of positive number is “<<sum;
return 0;


Enter a number 10
Enter a number -5
The sum of positive number is 10

2 thoughts on “While Loop in C++”

  1. Pingback: For loop in C++ - AskAtul.com

  2. Pingback: do-While loop in C++ - AskAtul.com

Leave a Comment

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