While Loop

C++BasicsInputArithmeticConditionsLoopsfor loop → The while loop

The while loop in C++. Construction and Examples. The while loop is used when we have to run a program over and over again, and not know for how many of times.

Construction: The while loop

while(condition)
{
Statement(s)
}

The while loop runs until the given condition is true. For example the following program will run forever because the given condition 10>5 will remain true.

#include <iostream>
using namespace std;
int main()
{
while (10>5)
{
cout << "I will run forever" << endl;
}
return 0;
}

The following program will run until the given condition is true (10>number). And stops when the condition is not true.

#include <iostream>
using namespace std;
int main()
{
int number = 0;
while (10>number)
{
cout << "I will run until 10 is greater than " << number << endl;
number++;
}
return 0;
}

number++ means add 1 to the variable number. So, each time when the loop runs, it adds 1 to the number. Hence, the variable number is increased by 1 each time.
Initially the number = 0. When the loop runs for the first time the number = 1. And, when loop runs for the second time, the number = 2. And so on. The loop stops before the number is 10. Because in this case the condition (10>number) is not true.

Q 1. Write a program in C++ using while loop, that take an input from user and shows cube of that number. And the program ends when the input is 10.

#include <iostream>
using namespace std;
int main()
{
int a;
cout <<"Enter a number: "; cin >>a;
int cube=a*a*a;
while (a!=10)
{
cout << cube;
break;
}
}

Q 2. Write a program in C++ using while loop that starts from 0, increase 1 by 1, and end before 10 using while loop in C++.

#include <iostream>
using namespace std;
int main()
{
int a=0;
while (a<9)
{
a=a+1;
cout << a;
}
}

a is less than 9 (a<9) in while loop. So it will stop at 8. And, as a=a+1 the answer will be 9. Hence, it will stop before 10.

If we want to show the result in vertical format, then the code is

#include <iostream>
using namespace std;
int main()
{
int a=0;
while (a<9)
{
a=a+1;
cout << a << endl;
}
}

Q.3 Write a program in C++ that takes an input from the user and shows how many times 2 is multiplied to be equal to or exceeds this number. That is, Find k in 2k when it is equal to or greater than the given number.

#include <iostream>
using namespace std;
int main()
{
int a = 1;
int times = 0;
int b;
cout << " Please enter a number: " << endl; cin >> b;
while ( a < b )
{
a = 2*a;
times++;
}
cout << times << endl;
}

And if, how many times 2 is multiplied to be nearest but less than this number. That is, Find k in 2k when it is less than the given number.

#include <iostream>
using namespace std;
int main()
{
int a = 1;
int times = 0;
int b;
cout << "Please enter a number: " << endl; cin >> b;
while ( a < b )
{
a = 2*a;
times++;
}
cout << times-1 << endl;
}

NEXT: The do-while loop