While Loop in C++ | Topic 10 | VU Insider

The Scenario

Let's say you have to calculate the sum of first 10 whole numbers. It means adding numbers 1 to 10. In C language, the following can be the way of doing it:
cout<<"Sum of first 10 whole numbers = "<<1 b="">code-box

The method is fine as the syntax is right. But what would be the scenario when you were asked to calculate the some of first 100 whole numbers or 1000.

This can be resulted in boring and messy statement. To overcome this situation, we rather use loop structures in C language.

While Loop in C++

It loops through the code block as long as specified condition is true.

In while loop, the condition is tested first and the statements are executed when the condition is true.

"while (expression/condition) {

"Int i = 0;
while (i < 10) {
cout << i <<"\n";

Another example: To calculate sum of first 1000 whole numbers
"int sum, number;
sum = 0;
num = 1;
while (number < 1000) {
sum = sum + number;
number = number + 1;
cout<<"The sum of first 100 whole numbers = "<code-box

The output will be "The sum of first 100 whole numbers = 500500".

Post a Comment

Previous Post Next Post