C++ while Loop
while is iterative statement in C++. It is used to execute statement or set of statements for a number of times. The number of iteration may be fixed in source code or may depend on variable. This value of variable can be result of any computation or may be an input from user.
Syntax
Initialization
while ( condition ) {
statements;
increament / decrement ;
}
Initialization
Initialization is the process of assigning starting value for the counter variable. This may be any numeric value.
Condition
Condition is the relational or logical expression that returns either TRUE or FALSE. Loop repeatedly execute statements while the given expression remains TRUE. Condition is enclodes in parentheses. If there is only single statement with while statement then there is no need to enclose statement in curly parentheses.
Statements
Statement are the valid C++ statements that ends with semicolon ( ; ). These statements may include:
-
Input Statements
-
Output Statements
-
Declarations
-
Expressions
-
Other Iterative statements
Increament / Decrement
This statement is used to increase or decrease the value of Counter Variable. If this statement does not written in body of loop then loop may goes infinite time. This statement may be written anywhere in body of loop.
Example
Example of while loop using Dev-C++ is as:
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// initialization.
int a = 1;
// while loop statement.
while ( a <= 5 ) {
// output statement.
cout<<"IMS\n";
// increment.
a = a + 1; // a++ can also be used.
}
return 0;
}