I am doing a project where I have to make a random number guessing game. The program works fine but just for habit learning, how can I make this program more efficient?
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <string>
#include <time.h>
int master(int username, int max);
usingnamespace std;
int main()
{
srand (time(NULL)); //seeds random number generator
int guessNum = rand() %100+1;
int attempt = 0;
int guess;
bool winner = false;
bool goOn = true;
string username;
string answer;
cout << "Please type name" << endl;//introduction
cin >> username;
cout << "Hello " <<username<< "! I am thinking of a number between 1 and 100!\nYour job is to guess what number I am thinking of!" <<endl;
cout << "You can begin guessing below" << endl << endl;
while(winner == false)//guessing
{
cin >> guess;
attempt++;
if (guess > guessNum)
{
cout << "To high!\n\n";
}
elseif (guess < guessNum)
{
cout << "To low!\n\n";
}
else
{
cout << "You won! You got it in " << attempt << " guesses!\n";
winner = true;
}
}
while(goOn) //continue or note
{
cout << "Would you like to play again? [y/n]\n";
cin >> answer;
if (answer == "y")
{
goOn = false;
main();
}
elseif (answer == "n")
{
return 0;
}
else
{
cout << "Make sure to type in either lowercase y or lowercase n" <<endl;
}
}
system ("pause");
}
#include <iostream>
#include <time.h>
usingnamespace std;
int main()
{
bool playing= true, guessing = true;
int guess, number;
srand(time(0));
do
{
number = rand() % 100 + 1;
cout << "Im thinking of a number between 1 and 100, try guess it: ";
do
{
cin >> guess;
if (guess == number)
guessing = false; // we guessed it
elseif (guess > number)
cout << "Too High!" << endl;
else
cout << "Too Low!" << endl;
} while(guessing);
cout << "Well done you got it, it was " << number << endl;
// here you could ask the question do they want to play again
// and if no, just set playing to false.
} while (playing);
return 0;
}
This is the second time in the last week or so I've seen someone post code calling main(). It's not even legal C++! What compiler are you using that allows this?
Anyways, on topic now:
OP, your program is too short and doesn't really do anything of significance, so there won't be anything to improve on efficiency wise.
Thinking about efficiency is a good habit to be in, but right now just continue writing code and improving yourself. You will know when you write something needs to be more efficient, and you likely will have ideas of how to improve it.
Although Visual Studio lets you place main() as a function call you will end up with a warning telling you that this would result in a runtime stack overflow - its not legal as ResidentBiscuit said and shouldnt be used.
Warnings are just as important as errors, you should take note of them and act on them. Anyway, Visual Studio would show something like this:
warning C4717: 'main' : recursive on all control paths, function will cause runtime stack overflow