Number guessing game code snippet
Summary
Source code
C++: number_guessing_game.cpp
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main() {
int secretNumber = 0;
// initialize randomizer
srand(time(0));
// propose a number in range 0-99
secretNumber = rand() % 100;
// loop
bool guessIsRight = false;
do {
int guess;
cout << "Your guess (0-99): ";
cin >> guess;
if (guess < secretNumber)
cout << "Too low!" << endl;
else if (guess > secretNumber)
cout << "Too high!" << endl;
else
guessIsRight = true;
} while (!guessIsRight);
// print a message
cout << "Congratulations! Your guess is right!" << endl;
return 0;
}
C: number_guessing_game.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int secretNumber = 0;
int guessIsRight = 0;
int guess;
/* initialize randomizer */
srand(time(0));
/* propose a number in range 0-99 */
secretNumber = rand() % 100;
/* loop */
do {
printf("Your guess (0-99): ");
scanf("%d", &guess);
if (guess < secretNumber)
printf("Too low!\n");
else if (guess > secretNumber)
printf("Too high!\n");
else
guessIsRight = 1;
} while (!guessIsRight);
/* print a message */
printf("Congratulations! Your guess is right!\n");
return 0;
}
Sample run
C/C++
Your guess (0-99): 15
Too low!
Your guess (0-99): 50
Too high!
Your guess (0-99): 25
Too low!
Your guess (0-99): 35
Too high!
Your guess (0-99): 30
Too low!
Your guess (0-99): 32
Too low!
Your guess (0-99): 33
Congratulations! Your guess is right!