Lesson 11: Case study – Using loops to make a simple number guessing game

[spoiler title=”Lesson Video”]
Direct Download of Video (For mobile / offline viewing)(right click > save target as)


[/spoiler]

[spoiler title=”Lesson Source Code”]

#include <iostream>
#include <cstdlib>
#include <time.h>
 
using namespace std;
 
 
int main(){
 
 
  //  Generate a random number
  //  Ask the user to guess the number
  //  For each guess we will tell the user if they are too high, or too low
  //  if( value == ourValue){ break; }
  //  While loops to control the flow of the game
  //  We're going to ask if they want to play again, before they exist
  srand(time(NULL));
  char quit = ' ';
  bool run = true;
 
  while (run){
    int secret = rand() % 1000 + 1;
    int guess = 0;
    while (guess != secret){
      do{
        cout << "Enter a number between 1 and 1000: ";
        cin >> guess;
      } while (guess < 1 || guess > 1000);
      if (guess < secret){
        cout << "\nYou have guessed a number that is too low.  ";
      }
      if (guess > secret){
        cout << "\nYou have guessed a number that is too high.  ";
      }
      if (guess == secret){
        cout << "\nCongratulations you guessed right  ";
      }
    }
 
    cout << "Would you like quit y/n: "; 
    cin >> quit;
    if (quit == 'y'){
      run = false;
    }
  }
 
  return 0;
}
  

[/spoiler]

Homework: http://beginnerscpp.com/forums/index.php/topic,63.0.html



Number guessing game
This number guessing game is an example of the type of program you can make with what you’ve learned up to this point with C++ using loops, and if statements. You could easily make far more complex games than this, but for a 15 minute (self-imposed) time limit, it’s not too bad. We cover a few concepts in this video that I want to put into writing.

Sentinel Loops
While we don’t directly use a sentinel loop in our program we use a bool to do roughly the same thing. A sentinel loop is a loop that is “broken” (exited) when a specific value becomes true. In this case we’re checking our variable “quit” to see if it becomes equal to y, then setting a boolean variable to false. The more ‘classic’ implementation of a sentinel loop is something like this:

...

while ( num != -999){
    cout << "Num = " << num << endl;
    cout << "Enter another value or -999 to exit";
    cin >> num; 
}