c++ simple car game
Here is an example of a simple car game written in C++ with explanations for each step:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
// Generate a random number between 1 and 100
srand(time(0));
int target = rand() % 100 + 1;
int guess;
int tries = 0;
cout << "Welcome to the Car Game!" << endl;
do {
cout << "Enter your guess (1-100): ";
cin >> guess;
if (guess < target) {
cout << "Too low! Try again." << endl;
} else if (guess > target) {
cout << "Too high! Try again." << endl;
}
tries++;
} while (guess != target);
cout << "Congratulations! You guessed the correct number in " << tries << " tries." << endl;
return 0;
}
Explanation:
We include the necessary libraries: iostream for input/output, cstdlib for random number generation, and ctime for seeding the random number generator.
We define the main function, which is the entry point of the program.
We seed the random number generator using
srand(time(0))
to ensure different random numbers are generated on each run.We generate a random number between 1 and 100 using
rand() % 100 + 1
and store it in the variabletarget
.We declare the variables
guess
to store the user's guess andtries
to keep track of the number of tries.We output a welcome message to the user.
We enter a do-while loop that continues until the user guesses the correct number.
Inside the loop, we ask the user to enter a guess using
cin >> guess
.We check if the guess is lower than the target number and display a corresponding message.
We check if the guess is higher than the target number and display a corresponding message.
We increment the
tries
variable to keep track of the number of tries.We repeat the loop as long as the guess is not equal to the target number.
Once the user guesses the correct number, we display a congratulatory message along with the number of tries it took.
We return 0 to indicate successful program execution.
This simple car game allows the user to guess a randomly generated number and provides feedback on whether the guess is too high or too low. The game continues until the user guesses the correct number, and the program keeps track of the number of tries.