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

  1. Include necessary header:

C

#include <stdio.h>
#include <stdlib.h>  // For the rand() function
  1. Initialize variables:

C

int secretNumber, guess, attempts = 0;
  1. Generate the secret number:

C

srand(time(NULL));  // Seed the random number generator
secretNumber = rand() % 100 + 1;  // Generate a number between 1 and 100
  1. 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++;
}
  1. 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.

CodeForHunger

Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button