Hello!!… in this mastery, I will show you how to use while.. and how does it works!.

  • First, what function does while has?: what it does is that as long as the parameter is true, whatever is inside while will repeat itself… a LOOP
  • To show you how to use it I will use the WSQ06, Random numbers.
  • Explaining while starts in  step 3.

1.- You start as always, but these time because we need to generate a random number we need few extras, like <cstdlib> and <time>.

while1

2.- Now we create our int main, inside there is and int that will the number we input, then we use srandn (time(NULL)),  and we asing the value rand () % 100 +1, to generate the random number, and then we ask the user to input a number.

while2

3.-NOW THE FUN PART.. WHILE*** here I wrote while (x!=r) to say that as long as r(random) is not the same as x (the number we input) the statements inside while must repeat, this is called a loop.

while3

4.Now we said what we want to repeat, when r is not equal to x, first I use and if (x>r) when the value we input is bigger than the random the output will be “the number is too high”

And if (x<r), when the value we input is smaller than the random, the output will be, “the number is too low”.

while4

5.- And finaly, the last statement, if (x==r), when the number we input is the same as the random, the output will be “Thats the number”

So now you know how while works… its really simple once you know how to write it 🙂

puppet

CC BY 4.0 Mastery 19: Use of loops with “while”. by Samantha Rivera is licensed under a Creative Commons Attribution 4.0 International License.