Create Guess the Number Game in C

Faraz

By Faraz -

Learn how to create a simple 'Guess the Number' game in C programming with easy-to-follow steps. Perfect for beginners. Start coding your own game today!


create-guess-the-number-game-in-c.webp

Introduction

Creating a "Guess the Number" game in C programming is an excellent way to sharpen your coding skills. This project is simple yet effective for beginners to understand basic concepts like loops, conditional statements, and random number generation in C. In this game, the computer picks a random number, and the player tries to guess it. The program gives hints to the player by indicating whether the guessed number is too high or too low.

In this step-by-step guide, you will learn how to create this game, compile it, and run it on your computer. Let's get started!

Step-by-Step Guide to Create Guess the Number Game in C

Step 1: Set Up Your Development Environment

Before you start coding, make sure you have a C compiler installed on your computer. You can use IDEs like Code::Blocks, Dev-C++, or even the GCC compiler on Linux. If you haven't installed any C compiler, follow these quick steps:

  1. Download a C compiler: Choose an IDE or a standalone compiler based on your operating system.
  2. Install the C compiler: Follow the on-screen instructions to complete the installation.
  3. Set up the IDE: If using an IDE like Code::Blocks, create a new project and choose "Console Application" in C.

Step 2: Start Coding the Game

Now, let's start coding the "Guess the Number" game. Open your IDE or a text editor and follow these steps:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    int number, guess, attempts = 0;
    srand(time(0));  // Seed for random number generator
    number = rand() % 100 + 1;  // Generate a random number between 1 and 100
    
    printf("Welcome to the Guess the Number Game!\n");
    printf("I have selected a number between 1 and 100.\n");
    printf("Can you guess it? Let's find out!\n");

    do {
        printf("Enter your guess: ");
        scanf("%d", &guess);
        attempts++;

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

    return 0;
}

Step 3: Save Your Program

Once you have written the code, save the file with a .c extension, such as guess_the_number.c. This will ensure that the file is recognized as a C source code file.

Step 4: Understanding the Code

  • Header Files: The program begins with #include <stdio.h>, which includes standard input-output functions, and #include <stdlib.h>, which includes the random number generation functions. The #include <time.h> library is used to seed the random number generator with the current time.
  • Variables: number stores the random number, guess is for storing the user's guess, and attempts keeps track of how many tries the user takes.
  • Random Number Generation: srand(time(0)) ensures that the random number is different every time the program is run. rand() % 100 + 1 generates a random number between 1 and 100.
  • Game Loop: The do...while loop continues until the user guesses the correct number. The program provides feedback if the guess is too high or too low.

Step 5: Adding a User Interface Menu (Optional)

For a more interactive experience, you can add a simple text-based menu to start or exit the game:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void startGame();

int main() {
    int choice;

    do {
        printf("\n===============================\n");
        printf("      Guess the Number Game     \n");
        printf("===============================\n");
        printf("1. Start Game\n");
        printf("2. Exit\n");
        printf("===============================\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                startGame();
                break;
            case 2:
                printf("Thank you for playing!\n");
                break;
            default:
                printf("Invalid choice! Please try again.\n");
        }
    } while (choice != 2);

    return 0;
}

void startGame() {
    int number, guess, attempts = 0;
    srand(time(0));
    number = rand() % 100 + 1;

    printf("I have selected a number between 1 and 100.\n");

    do {
        printf("Enter your guess: ");
        scanf("%d", &guess);
        attempts++;

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

Step 6: Compiling the Program

Once you have saved your program, you need to compile it to create an executable file. Here’s how you can compile the program:

  1. Using GCC (Linux/Windows with MinGW):
    • Open the terminal or command prompt.
    • Navigate to the directory where your guess_the_number.c file is saved.
    • Run the following command to compile the program:
      gcc guess_the_number.c -o guess_the_number
    • This command generates an executable file named guess_the_number.
  2. Using an IDE (e.g., Code::Blocks):
    • Open your project in the IDE.
    • Click on "Build" or press F9 to compile the code.
    • The IDE will automatically compile the program and generate the executable.

Step 7: Running the Program

After compiling the program, you can run the executable file to start the game. Here’s how:

  1. Using Command Prompt/Terminal:
    • Run the following command:
      ./guess_the_number  (Linux/Windows with MinGW)
      guess_the_number.exe (Windows)
    • The game will start, and you can begin guessing the number.
  2. Using an IDE:
    • After compilation, click on "Run" or press Ctrl+F10 in most IDEs.
    • The console will open, and the game will start.

Conclusion

Congratulations! You've successfully created a "Guess the Number" game in C programming. This project is a great starting point for beginners to understand basic programming concepts like loops, conditionals, and random number generation. By following this guide, you've learned how to set up a development environment, write the code, compile it, and run the program.

This simple game can be expanded with more features, like allowing the user to set the range of numbers, or keeping track of the best score. Keep experimenting and learning as you continue your journey into C programming!

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺