C++: Guess the Number


The task is to write a program where the program chooses a number between 1 and 10. A player is then prompted to enter a guess. If the player guess wrong then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will give a “Well guessed!” message, and the program will exit.

A conditional loop may be used to repeat the guessing until the user is correct.

#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
	int n = 1 + (rand() % 10);
	int g;
	std::cout << "I'm thinking of a number between 1 and 10.\nTry to guess it! ";
		std::cin >> g;
		if (g == n)
		std::cout << "That's not my number.\nTry another guess! ";
	std::cout << "You've guessed my number!";
	return 0;


Content is available under GNU Free Documentation License 1.2.