how to guess random numbers in c++ code example

Example 1: c++ guess my number

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
	int num, guess, tries = 0;
	srand(time(0)); //seed random number generator
	num = rand() % 100 + 1; // random number between 1 and 100
	cout << "Guess My Number Game\n\n";

	do
	{
		cout << "Enter a guess between 1 and 100 : ";
		cin >> guess;
		tries++;

		if (guess > num)
			cout << "Too high!\n\n";
		else if (guess < num)
			cout << "Too low!\n\n";
		else
			cout << "\nCorrect! You got it in " << tries << " guesses!\n";
	} while (guess != num);

	return 0;
}

Example 2: guessing game c++

#include <iostream>
#include <cstdlib>
#include <ctime>
using std::cout;
using std::cin;
using std::endl;


int main() {

    long int randnum,guess,lowerlimit,higherlimit = 0 ;
    srand(time(NULL));

    do
    {
    cout<<"enter your lower limit number: ";
    cin>> lowerlimit ;
    cout<<"enter your higher limit number:";
    cin>>higherlimit;
    cout<<"enter your guessing number between: " <<"  "<< lowerlimit << " and "<<""<<higherlimit<<" : ";
    cin>>guess;
    randnum = rand()%(higherlimit-lowerlimit+1) + lowerlimit ;  
    // using the conditional operator instead of if / else  
    if(guess != randnum){
        cout <<((guess > randnum)? "your guess is large  " : "your guess is too small " ) << "and it is " << guess << " and computer guess is " << randnum << endl;

    }else
        cout << " GREAT, YOU WON !!!"<<", your guess is " << guess << " and computer guess is " << randnum << endl;
        
    }while(guess!=randnum);
    
    
    return 0 ; 

}

Tags:

Cpp Example