48 lines
1.2 KiB
C++
48 lines
1.2 KiB
C++
#include <iostream>
|
|
#include <stdlib.h>
|
|
|
|
using namespace std;
|
|
|
|
// Number guessing game
|
|
// Program should "pick" a random number and prompt
|
|
// us to guess it, responding with higher or lower as appropriate
|
|
// should print something like "You Win" and stop if you guess correctly
|
|
|
|
// steps:
|
|
// 1. generate number [check]
|
|
// 2. prompt for a guess
|
|
// 3. read in guessed number
|
|
// 4. check if the number is correct
|
|
// IF it is correct, stop the game
|
|
// else if it is greater, print "lower", go back to 2
|
|
// else print "higher", go back to 2
|
|
|
|
int main(){
|
|
srand(time(0));
|
|
int hiddenNumber = (rand() % 100) + 1;
|
|
int guess = -1;
|
|
int maxGuesses = 5;
|
|
int numGuesses = 0;
|
|
|
|
while((guess != hiddenNumber) && (numGuesses < maxGuesses)){
|
|
// code that runs inside while
|
|
cout << "Enter a number between 1 and 100: ";
|
|
cin >> guess;
|
|
if(guess > hiddenNumber){
|
|
cout << "Lower!" << endl;
|
|
}
|
|
else if(guess < hiddenNumber) {
|
|
cout << "Higher!" << endl;
|
|
}
|
|
numGuesses = numGuesses + 1; // numGuesses++
|
|
}
|
|
|
|
if( guess == hiddenNumber){
|
|
cout << "You win!" << endl;
|
|
}
|
|
else {
|
|
cout << "You ran out of guesses" << endl;
|
|
}
|
|
|
|
return 0;
|
|
} |