Introduction

Welcome to the “Number Guessing Game”! This is a simple program that allows you to play a fun game where the computer randomly selects a number, and your objective is to guess it correctly. It’s an excellent exercise to improve your logic-building skills, basic programming concepts, and understanding of randomness in C programming.

Objective

The goal of this game is for the computer to randomly select a number between a specified range (1 to 100 in this case). The player will have to input guesses until they correctly guess the number. After each guess, the computer will provide feedback on whether the guess was too high or too low.

Program Code

#include 
#include 
#include 

int main() {
    int targetNumber, userGuess, attempts = 0;

    // Initialize random number generator
    srand(time(0));

    // Generate a random number between 1 and 100
    targetNumber = rand() % 100 + 1;

    // Game title
    printf("Welcome to the Number Guessing Game!\n");
    printf("I have selected a number between 1 and 100. Can you guess it?\n");

    // Loop until the user guesses the number
    do {
        printf("Enter your guess: ");
        scanf("%d", &userGuess);

        attempts++;

        if (userGuess > targetNumber) {
            printf("Too high! Try again.\n");
        } else if (userGuess < targetNumber) {
            printf("Too low! Try again.\n");
        } else {
            printf("Congratulations! You've guessed the number in %d attempts.\n", attempts);
        }
    } while (userGuess != targetNumber);

    return 0;
}

Explanation of the Program Structure

The program starts by including necessary header files: stdio.h, stdlib.h, and time.h to handle input/output operations, random number generation, and time-based functions respectively.

The program then defines three variables:

  • targetNumber: The number that the computer randomly selects.
  • userGuess: The number guessed by the player.
  • attempts: A counter to track how many guesses the player has made.

Next, the random number generator is seeded using srand(time(0)); to ensure different results each time the program is run. The program then enters a loop, asking the user to input guesses until they correctly guess the number. After each guess, feedback is given, telling the player whether their guess was too high or too low.

Once the player guesses the correct number, a congratulatory message is displayed, along with the number of attempts it took to guess correctly.

How to Run the Program

  1. Copy the C code into a text editor (e.g., Notepad++) and save it as guessing_game.c.
  2. Open a terminal or command prompt and navigate to the directory where the file is saved.
  3. Compile the C program using a C compiler, e.g., gcc guessing_game.c -o guessing_game (assuming you have GCC installed).
  4. Run the compiled program using the command: ./guessing_game (on Linux/Mac) or guessing_game.exe (on Windows).
  5. Follow the on-screen prompts to start guessing!

Explanation of the Program Structure:

  1. Header Files:
    • stdio.h: For input and output operations (e.g., printfscanf).
    • stdlib.h: For functions related to random number generation (rand and srand).
    • time.h: To use time(0) to seed the random number generator, ensuring different outputs on each run.
  2. Variables:
    • targetNumber: The random number the computer selects.
    • userGuess: The guess entered by the user.
    • attempts: A counter to track the number of guesses.
  3. Random Number Generation:
    • The program uses rand() to generate a random number between 1 and 100. The seed for randomness is set by srand(time(0)).
  4. Game Loop:
    • The game runs in a do-while loop, where the user is asked to input a guess until they guess correctly. After each guess, the program compares the guess with the target number and gives feedback.
  5. User Feedback:
    • If the guess is too high, the program responds with “Too high! Try again.”
    • If the guess is too low, the program responds with “Too low! Try again.”
    • If the guess is correct, the program congratulates the user and displays the number of attempts.
  6. Running the Program:
    • The steps for compiling and running the program are listed in the HTML. The user can compile the C code with a C compiler like GCC and run the program.

How to Run:

  • Save the C code to a file named guessing_game.c.
  • Compile and run the program using a C compiler (e.g., GCC).
  • Follow the on-screen instructions to guess the number.
© 2024 Learn Programming. All Rights Reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)