C++ Program to guess a random number.
A basic C++ program.
Date Created:Friday December 29th, 2006 03:41 AM
Date Modified:Wednesday July 30th, 2008 11:43 PM
#include <iostream>
using namespace std;
// foo has to be an integer, due to the return statement in main()
int foo() {
int nRandomNum = rand()%11; // modulus 11 puts numbers between 0 and 10
int nUserInput = -1;
cout << "Enter a number between 0 and 10:" << endl;
cin >> nUserInput;
while (nUserInput != nRandomNum) {
if ( nUserInput > nRandomNum ) {
cout << "Too High!";
} else {
cout << "Too Low!";
}
cout << " Enter a number between 0 and 10:" << endl;
cin >> nUserInput;
}
cout << "You Win!" << endl;
return 0;
}
int main() {
// time requires argument of NULL
srand( time( NULL ) ); // srand() skips ahead or changes the seed, for and rand().
return foo();
}
/*
THIS USES A FOR LOOP AND GIVES USER 3 CHANCES TO GUESS
*/
#include <iostream>
using namespace std;
// foo has to be an integer, due to the return statement in main()
int foo() {
int nRandomNum = rand()%11; // modulus 11 puts numbers between 0 and 10
int nUserInput = -1;
cout << "Enter a number between 0 and 10:" << endl;
cin >> nUserInput;
for ( int i = 0; i < 3; i++ ) {
if ( nUserInput > nRandomNum ) {
cout << "Too High!";
} else if ( nUserInput < nRandomNum ) {
cout << "Too Low!";
} else {
// they guessed correct.
break;
}
if ( nUserInput != nRandomNum && i == 2 ) {
cout << " You Lose\n";
return 0; // stops executing.
}
cout << " Enter a number between 0 and 10:" << endl;
cin >> nUserInput;
}
cout << "You Win!" << endl;
return 0;
}
int main() {
// time requires argument of NULL
srand( time( NULL ) ); // srand() skips ahead or changes the seed, for and rand().
return foo();
}
Downloads:
Download: random_number_for_loop.cpp 1 KB
Download: random_number.cpp 783 B
Please login or Click Here to register for downloads
Guess Random Number by Dan Lynch
is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
Based on a work at www.3daet.com
Permissions beyond the scope of this license may be available at http://www.3daet.com
