Asked in C Programming
C Programming

How do you use the while code?

012

Answer

User Avatar
Wiki User
05/06/2008

while is a loop. The most common definition is

while (bool_condition)

{

...//your code here

}

where bool_condition is a variable of bool type or equality/unequality, for instance a==b, or a >= 0 and so. while woork as long as bool_condition has value true.

int index = 0;

while (index <10)

{

cout << index << endl;

index++;

}

This code will print on the screen all numbers from 0 to 9 including, when index equals 10 condition index < 10 becomes false and while passes the turn to the next element. The outcome of this code is:

0

1

2

3

4

5

6

7

8

9

each on a new line.

Also you can use the loop which is called do-while. It works different a little bit, and it looks like following:

do

{

//your code here

} while (bool_condition);

do

{

cout << index << endl;

index++;

} while (index <10);

The result will be

0

1

2

3

4

5

6

7

8

9

10

each on a new line. Difference between while and do-while is following. do-while alsways makes one extra loop because it checks bool condition after it ran the cycle, while loop does it before running the cycle. That's why you see one extra number 10 in outcome.