While loop is a general repetition statement in C++. The while statement will repeat the statements inside the while block as long as the expression evaluates to true.
while (expression)
{
Statement 1;
Statement 2;
Statement 3;
}
Here is an infinite loop that print from numbers starting from 0 and increments by 1. Infinite loop never ends because expression given in the while statement always evaluates to true.
#include <iostream>
using namespace std;
int main() {
int i = 0;
while (true)
{
cout << i << "\t";
i++;
}
return 0;
}
The following program will print from 1 - 10 seperated by tab. Note that variable 'i' is tested in the expression of the while statement. This variable should be declared and initialized before the while statement. Within the while loop, the variable 'i' should be changed allowing the loop to eventually terminate. This is an example of fixed-count loop where the counter 'i' controls the number of loops.
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 10)
{
cout << i << "\t";
i = i + 1;
}
return 0;
}
Output
Here is another example that prints 12th multiplication table using while loop:
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 12)
{
cout << i << " * 12 = " << i * 12 << "\n";
i++;
}
return 0;
}
Output:
Here is another program that is more interactive. The program ask user to enter the count of numbers to add together and then prompt the user to enter the numbers. Finally the program displays the sum of all numbers
#include <iostream>
using namespace std;
int main() {
int n,i = 1;
double num = 0, tot = 0;
cout << "How many numbers do you want to add: ";
cin >> n;
while (i<=n)
{
cout << "Enter number " << i << ":";
cin >> num;
tot = tot + num;
i++;
}
cout << "The total is: " << tot << endl;
return 0;
}
Output:
#include <iostream>
using namespace std;
int main() {
int j = 12;
while (j <= 15)
{
int i = 1;
while (i <= 12)
{
cout << i << " * " <<j<< " = " << i * j << "\n";
i++;
}
j++;
cout << endl;
}
return 0;
}
Output:
Comments
Post a Comment