Advanced Control Flow – While Loop

There is another type of loop similar to the for loop called the while loop. It executes instructions until the condition is met.

Introducing the While Loop

The structure is below.

while ( condition ) {

statements to be executed

}

Let’s make a guessing game where the user guesses a number and the user continues with the program until he guesses the correct number.

int guess;
int numberToGuess = 27;
cin >> guess;

while ( guess != numberToGuess ) {
cout << "Sorry! Wrong number.\nKeep Guessing!\n";
}

cout << "Congratulations you guessed the correct number!\n";

How it the While Loop works

It’s straightforward actually. It simply continues executing the statements until the condition is met. It’s very similar to the if statements. You can have multiple conditions to be satisfied in order for the program to break out of the while loop. An example is below.

int num1 = 25;
int num2 = 75;

int guess;

cout << "Pick a number between our mystery two numbers!";

cin >> guess;

while ( num1 < guess && num2 > guess  ) {
cin >> guess;
}

cout << "Congratulations you picked the correct range for your number!\n";

Further Practice with While Loops

Exercise 1: Make the user guess a magic number. Tell them if their number was either below or above the one they guess.

Exercise 2: Make the user guess a magic number. If they got it correct. Make them guess a second magic number. If they don’t get it right the first time, they start again!

*Hint: You can do it with 2 while loops.

Challenge 1: Determine if a word is a palindrome. What is a palindrome? mom, racecar, dad…

*Hint: Something found here will help you out solve this problem!

Related Posts

No comments yet... Be the first to leave a reply!