On this mastery I’m going to show you what “while” loop in C++ is and how to use it.

The while loop consists of something happens WHILE a condition is given. For example: WHILE x is greater or equal than 0, something will happen, and this process will continue to happen WHILE this condition is true.

For the purpose of these mastery, we will use a function and a while loop to continue printing a character while the condition is true. 

We want to print n amount of hashtags (#) because we really LOVE hashtags. So the user will input the amount of hashtags he wants to print and the program should be able to print that amount of hashtags. So, do as follows:

  1. Write our “basic code” and leave some space to write a function as we learn on masteries 11 and 12.
  2. Write a function of type CHAR (because we will use characters) that prints a # when you return its value.
  3. Inside int main (), declare the variable, and ask the user for it.
  4. Now, we will use the WHILE loop. So until now, your code should look something like this:

Now, for the WHILE loop, we want to ask the user for an x amount of times the character # will print, so we need this:

The code inside the while loop will continue to happen until x = 0. So your code should work like this:

And that’s about it, you now know how to use while loop with a function, congrats!

CC BY 4.0 Mastery 19 by Omar Peza is licensed under a Creative Commons Attribution 4.0 International License.