I created a Number Guessing Game in C++. I used random header file along with iostream which is obviously needed for input and output process.

uniform_int_distribution<>dist(0,size-1);

dist(gen)

Then I entered some rules:

I added a if-else statement to take a number between 1-10 from the user and if the user enter wrong number then it will say “Enter a valid number”.

In that if, I have nested another if-else statement where the computer generated index and user entered number’s index is matched for the rules of the game.

At last to end the game or to continue it I used switch statement. If the user enters 1 then the game will continue and if the user enters 0 then the program will end.

Code:

#include<iostream>
#include<random>
using namespace std;

int main(){
	int arr[]={1,2,3,4,5,6,7,8,9,10};
	int size=sizeof(arr)/sizeof(arr[0]);
	int num;
	int ag;
	
	cout<<"::Number Guessing Game::"<<endl;
	cout<<"Enter a number between 1 to 10"<<endl;
	cout<<"If the number entered by you is same number guessed by the computer then computer wins"<<endl;
	cout<<"Else you win"<<endl;
  cout<<"At last if you want to play again enter 1 or don't want then enter 0"<<endl;
	
	again:
		random_device rd;
		mt19937 gen(rd());
		uniform_int_distribution<>dist(0,size-1);
	
		int randomIndex=dist(gen);

		cout<<endl<<"Enter a number: ";
		cin>>num;

		if( (num>=1)&&(num<=10) ){
	    	cout<<"Guess by Computer: "<<arr[randomIndex]<<endl;
	    	if(num==arr[randomIndex]){
	        	cout<<"Computer Wins"<<endl;
	    	}else cout<<"You Win"<<endl;  
		}else{
	    	cout<<"Enter a valid number"<<endl;
				goto again;
		}

	opr:
		cout<<"Want to play again: ";
		cin>>ag;

	switch(ag){
		case 1:
			goto again;
			break;
		case 0:
			cout<<"Program Executed";
			break;
		default:
			cout<<endl<<"Invalid Operator"<<endl;
			cout<<"Enter a Valid Operator"<<endl;
			goto opr;		
	}
	
	return 0;
}

Output: