C (programming language)
Guess the Number Game in C (Project 2)
Introduction
- In this project, we’ll create a classic “Guess the Number” game using C programming.
- The game involves the computer generating a random number, and the player attempting to guess it within a limited number of attempts.
- It reinforces fundamental C concepts such as:
- Variables
- Input/output
- Conditional statements
- Loops
- Random number generation
Steps to Create the Game
- Include necessary header:
C
#include <stdio.h>
#include <stdlib.h> // For the rand() function
- Initialize variables:
C
int secretNumber, guess, attempts = 0;
- Generate the secret number:
C
srand(time(NULL)); // Seed the random number generator
secretNumber = rand() % 100 + 1; // Generate a number between 1 and 100
- Start the game loop:
C
while (attempts < 5) {
// Get player's guess
printf("Guess a number between 1 and 100: ");
scanf("%d", &guess);
// Check the guess
if (guess == secretNumber) {
printf("Congratulations! You guessed the number in %d attempts!\n", attempts + 1);
break; // Exit the loop if correct
} else if (guess < secretNumber) {
printf("Too low! Try again.\n");
} else {
printf("Too high! Try again.\n");
}
attempts++;
}
- Handle game ending:
C
if (attempts == 5) {
printf("Sorry, you ran out of attempts. The number was %d.\n", secretNumber);
}
Complete Code:
C
#include <stdio.h>
#include <stdlib.h>
int main() {
// ... (code from previous steps)
return 0;
}
Additional Features and Enhancements:
- Difficulty levels: Adjust the number range or attempts for different difficulty settings.
- Hints: Provide clues based on the player’s previous guesses (e.g., “warmer” or “colder”).
- Customizable game settings: Allow players to choose the number range and number of attempts.
- Visual elements: Add creative text-based graphics or animations to enhance the visual appeal.
- High scores: Track and display player scores and rankings for replayability.