while loop statement over and over executes an objective assertion up to a given condition is true.

cpp while loop


Syntax:-
while(condition)
{
statement(s);
}

Here, statement(s) might be a single statement or a block of explanations. The condition might be any expression, and true is any non-zero worth. The loop emphasizes while the condition is valid.

At the point when the condition turns out to be false, program control passes to the line promptly following the loop

Example: Sum of Positive Numbers Only

/*
program to find the 
sum of positive numbers 
*/
/*
if the user enters a negative number,
the loop ends 
*/
/*
the negative number entered is 
not added to the sum 
*/
#include <iostream>
using namespace std; 
int main() 
{ 
int number; 
int sum = 0; 
// take input from the user 
cout << "Enter a number: "; 
cin >> number; 
while (number >= 0) {
 // add all positive numbers 
sum += number; 
//take input again if the number is positive 
cout << "Enter a number: "; 
cin >> number; 
} 
// display the sum 
cout << "\nThe sum is " << sum << endl; 
return 0; 
}

Output:-
Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2
The sum is 25

Previous                                                                                             Next