The While loop


1. While block

One of three loops which you can use in C++ programming language is while loop. The while loop is mostly used for repeating the segments of code in which repetition is not predetermined. Syntax of the while block is given below.
While (condition)
// command_block
The condition in brackets is the variable of bool type which means it returns the result of type true or false. When the program executes the while loop he firstly calculates the value of the condition. If the condition is true than the program executes the command block. After the execution of the command block program repeats the while loop. If the condition result is false then the program skips the command block and executes the first command after the command block.


Now we will use while block to create a counter from zero to 10000 so start a new project and copy the following code.
// While block.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
            int x = 0;
            while ( x < 10000 )
                        cout << x++ << endl;
            x++;
            return 0;
}

First of all we have used standard libraries and we have declared namespace std to include the basic commands such as cout, cin and endl. After the function main we have declared the integer variable x and assign 0 to variable x. In while loop we have set the condition which in this case is that the variable x must always be smaller than 10000. If you look this program code logically the condition will always be true until the number 9999. After that number the program will stop because variable x cannot be equal to 10000.
After writing the code click on the button “Start Debugging” and after that click Ctrl+F5 to run the program. If you entered your code correctly there shouldn't be any problem with debugger. Otherwise the debugger will report an error which means that program has the syntax error or semantic error (wrongly structured). The program is shown in the next picture.

Share on Google Plus