Simple Number Guessing Game in C: Building Your First Interactive Program

Creating a number guessing game is a classic beginner project that teaches fundamental programming concepts in C: random number generation, user input, loops, conditionals, and game logic. This simple yet engaging program provides immediate feedback and can be expanded with features like difficulty levels, scoring, and replayability.

What is a Number Guessing Game?

A number guessing game is an interactive program where the computer selects a random number within a range, and the player tries to guess it. After each guess, the program provides hints ("Too high" or "Too low") until the player guesses correctly. The game then displays the number of attempts and offers to play again.

Why Build a Number Guessing Game?

  1. Learn Core Concepts: Practice variables, input/output, loops, and conditionals.
  2. Random Number Generation: Understand how to generate unpredictable values.
  3. User Interaction: Handle real-time user input and provide feedback.
  4. Game Logic: Implement win/lose conditions and scoring.
  5. Code Organization: Structure a complete program from start to finish.

Basic Number Guessing Game

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
int main() {
// Seed the random number generator with current time
srand(time(NULL));
// Generate random number between 1 and 100
int secretNumber = rand() % 100 + 1;
int guess;
int attempts = 0;
printf("========================================\n");
printf("    WELCOME TO THE NUMBER GUESSING GAME\n");
printf("========================================\n");
printf("I'm thinking of a number between 1 and 100.\n");
printf("Can you guess what it is?\n\n");
// Game loop - continues until player guesses correctly
do {
printf("Enter your guess: ");
scanf("%d", &guess);
attempts++;
if (guess < secretNumber) {
printf("Too low! Try again.\n\n");
} else if (guess > secretNumber) {
printf("Too high! Try again.\n\n");
} else {
printf("\nCongratulations! You got it!\n");
printf("The secret number was %d\n", secretNumber);
printf("It took you %d attempts.\n", attempts);
}
} while (guess != secretNumber);
printf("\nThanks for playing!\n");
return 0;
}

Enhanced Version with Multiple Features

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include <ctype.h>
// Function prototypes
int getDifficultyRange(int difficulty);
void playGame(int maxNumber, int maxAttempts);
bool playAgain();
void displayRules();
int getValidInput(int min, int max);
int main() {
srand(time(NULL));
printf("============================================\n");
printf("     ADVANCED NUMBER GUESSING GAME\n");
printf("============================================\n");
int choice;
bool keepPlaying = true;
while (keepPlaying) {
printf("\nMAIN MENU:\n");
printf("1. Play Game\n");
printf("2. View Rules\n");
printf("3. Exit\n");
printf("Enter your choice: ");
choice = getValidInput(1, 3);
switch (choice) {
case 1: {
// Select difficulty
printf("\nSELECT DIFFICULTY:\n");
printf("1. Easy (1-50, unlimited attempts)\n");
printf("2. Medium (1-100, 10 attempts)\n");
printf("3. Hard (1-200, 7 attempts)\n");
printf("4. Expert (1-500, 5 attempts)\n");
printf("Enter difficulty: ");
int difficulty = getValidInput(1, 4);
int maxNumber;
int maxAttempts;
switch (difficulty) {
case 1:
maxNumber = 50;
maxAttempts = 999; // Effectively unlimited
break;
case 2:
maxNumber = 100;
maxAttempts = 10;
break;
case 3:
maxNumber = 200;
maxAttempts = 7;
break;
case 4:
maxNumber = 500;
maxAttempts = 5;
break;
}
playGame(maxNumber, maxAttempts);
break;
}
case 2:
displayRules();
break;
case 3:
keepPlaying = false;
printf("\nThanks for playing! Goodbye!\n");
break;
}
}
return 0;
}
// Main game function
void playGame(int maxNumber, int maxAttempts) {
int secretNumber = rand() % maxNumber + 1;
int guess;
int attempts = 0;
int score = 100; // Starting score
bool guessedCorrectly = false;
printf("\n========================================\n");
printf("   NEW GAME - Guess 1-%d\n", maxNumber);
if (maxAttempts < 999) {
printf("   You have %d attempts\n", maxAttempts);
} else {
printf("   Unlimited attempts\n");
}
printf("========================================\n");
while (attempts < maxAttempts && !guessedCorrectly) {
printf("\nAttempt %d", attempts + 1);
if (maxAttempts < 999) {
printf(" of %d", maxAttempts);
}
printf("\nEnter your guess: ");
// Input validation
while (scanf("%d", &guess) != 1) {
printf("Invalid input! Please enter a number: ");
while (getchar() != '\n'); // Clear input buffer
}
// Clear input buffer
while (getchar() != '\n');
// Validate range
if (guess < 1 || guess > maxNumber) {
printf("Please enter a number between 1 and %d.\n", maxNumber);
continue;
}
attempts++;
if (guess < secretNumber) {
printf("πŸ“ˆ Too low!");
if (abs(secretNumber - guess) < 10) {
printf(" (but you're getting close!)");
}
printf("\n");
score -= 2; // Penalty for wrong guess
} else if (guess > secretNumber) {
printf("πŸ“‰ Too high!");
if (abs(secretNumber - guess) < 10) {
printf(" (but you're getting close!)");
}
printf("\n");
score -= 2; // Penalty for wrong guess
} else {
guessedCorrectly = true;
printf("\nπŸŽ‰ CONGRATULATIONS! πŸŽ‰\n");
printf("You guessed the number %d correctly!\n", secretNumber);
printf("Attempts: %d\n", attempts);
// Calculate final score
if (maxAttempts < 999) {
score = score - (attempts * 2) + (maxAttempts - attempts) * 5;
} else {
score = 100 - attempts * 2;
}
if (score < 0) score = 0;
printf("Final score: %d\n", score);
// Performance feedback
if (attempts == 1) {
printf("⭐ PERFECT! First try! ⭐\n");
} else if (attempts <= maxNumber / 20) {
printf("Excellent guessing!\n");
} else if (attempts <= maxNumber / 10) {
printf("Good job!\n");
} else {
printf("You got it! Keep practicing!\n");
}
}
// Give hint after several attempts
if (!guessedCorrectly && attempts >= maxAttempts / 2 && maxAttempts < 999) {
if (secretNumber % 2 == 0) {
printf("πŸ’‘ Hint: The number is even.\n");
} else {
printf("πŸ’‘ Hint: The number is odd.\n");
}
}
}
// Game over - ran out of attempts
if (!guessedCorrectly) {
printf("\n😒 GAME OVER! You ran out of attempts.\n");
printf("The secret number was %d.\n", secretNumber);
printf("Better luck next time!\n");
}
}
// Ask if player wants to play again
bool playAgain() {
char response;
printf("\nWould you like to play again? (y/n): ");
scanf(" %c", &response);
while (getchar() != '\n'); // Clear input buffer
return (tolower(response) == 'y');
}
// Display game rules
void displayRules() {
printf("\n========================================\n");
printf("            GAME RULES\n");
printf("========================================\n");
printf("1. The computer will randomly select a number\n");
printf("   within your chosen difficulty range.\n\n");
printf("2. Your goal is to guess the number.\n\n");
printf("3. After each guess, you'll get feedback:\n");
printf("   - 'Too high' if your guess is above the number\n");
printf("   - 'Too low' if your guess is below the number\n\n");
printf("4. Different difficulty levels:\n");
printf("   - Easy: 1-50, unlimited attempts\n");
printf("   - Medium: 1-100, 10 attempts\n");
printf("   - Hard: 1-200, 7 attempts\n");
printf("   - Expert: 1-500, 5 attempts\n\n");
printf("5. Score is based on attempts and difficulty.\n");
printf("   Higher scores for fewer attempts!\n\n");
printf("6. Hints are provided when you're halfway through\n");
printf("   your allowed attempts.\n");
printf("========================================\n");
}
// Get validated integer input within range
int getValidInput(int min, int max) {
int input;
int valid = 0;
while (!valid) {
if (scanf("%d", &input) != 1) {
printf("Invalid input! Please enter a number: ");
while (getchar() != '\n'); // Clear input buffer
continue;
}
if (input >= min && input <= max) {
valid = 1;
} else {
printf("Please enter a number between %d and %d: ", min, max);
}
// Clear input buffer
while (getchar() != '\n');
}
return input;
}

Compact Version (Single File)

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int number, guess, attempts = 0;
char playAgain;
// Seed random number generator
srand(time(NULL));
do {
// Generate random number (1-100)
number = rand() % 100 + 1;
attempts = 0;
printf("\n=== Number Guessing Game ===\n");
printf("I'm thinking of a number between 1 and 100.\n");
// Game loop
do {
printf("Enter your guess: ");
scanf("%d", &guess);
attempts++;
if (guess < number) {
printf("Too low! Try again.\n");
} else if (guess > number) {
printf("Too high! Try again.\n");
} else {
printf("\nCorrect! The number was %d.\n", number);
printf("You got it in %d attempts!\n", attempts);
}
} while (guess != number);
// Ask to play again
printf("\nPlay again? (y/n): ");
scanf(" %c", &playAgain);
} while (playAgain == 'y' || playAgain == 'Y');
printf("Thanks for playing! Goodbye.\n");
return 0;
}

Version with Attempt Limit and High Score

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int number, guess, attempts;
int maxAttempts = 7;
int gamesPlayed = 0;
int bestScore = 999; // Initialize to high number
char playAgain;
srand(time(NULL));
printf("====================================\n");
printf("   NUMBER GUESSING CHALLENGE\n");
printf("====================================\n");
printf("You have %d attempts to guess the number.\n", maxAttempts);
printf("Can you beat the high score?\n\n");
do {
number = rand() % 100 + 1;
attempts = 0;
gamesPlayed++;
printf("\n--- Game %d ---\n", gamesPlayed);
printf("Guess the number (1-100):\n");
// Game loop with attempt limit
while (attempts < maxAttempts) {
printf("Attempt %d/%d: ", attempts + 1, maxAttempts);
scanf("%d", &guess);
attempts++;
if (guess < number) {
printf("⬆️ Too low!\n");
} else if (guess > number) {
printf("⬇️ Too high!\n");
} else {
printf("\nβœ… CORRECT! You got it in %d attempts!\n", attempts);
// Update high score
if (attempts < bestScore) {
bestScore = attempts;
printf("πŸŽ‰ NEW HIGH SCORE! πŸŽ‰\n");
}
break;
}
// Show remaining attempts
if (attempts < maxAttempts && guess != number) {
printf("   %d attempt%s remaining.\n", 
maxAttempts - attempts, 
(maxAttempts - attempts == 1) ? "" : "s");
}
}
// Out of attempts
if (attempts >= maxAttempts && guess != number) {
printf("\n❌ GAME OVER! The number was %d.\n", number);
}
printf("\nHigh Score: %d attempts\n", 
bestScore == 999 ? 0 : bestScore);
printf("\nPlay again? (y/n): ");
scanf(" %c", &playAgain);
} while (playAgain == 'y' || playAgain == 'Y');
printf("\nThanks for playing!\n");
printf("Total games: %d\n", gamesPlayed);
if (bestScore != 999) {
printf("Best score: %d attempts\n", bestScore);
}
return 0;
}

Two-Player Version

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void clearScreen() {
// Simple clear screen - works on most terminals
printf("\033[2J\033[1;1H");
}
int main() {
char player1[50], player2[50];
int secretNumber, guess;
int currentPlayer = 1;
int scores[3] = {0, 0, 0}; // Index 1 and 2 for players
int rounds;
char playAgain;
printf("========================================\n");
printf("       TWO-PLAYER GUESSING GAME\n");
printf("========================================\n");
// Get player names
printf("Enter Player 1 name: ");
fgets(player1, sizeof(player1), stdin);
player1[strcspn(player1, "\n")] = 0; // Remove newline
printf("Enter Player 2 name: ");
fgets(player2, sizeof(player2), stdin);
player2[strcspn(player2, "\n")] = 0; // Remove newline
printf("How many rounds? (1-5): ");
scanf("%d", &rounds);
if (rounds < 1) rounds = 1;
if (rounds > 5) rounds = 5;
// Seed random
srand(time(NULL));
for (int round = 1; round <= rounds; round++) {
clearScreen();
printf("\n=== ROUND %d ===\n", round);
// Determine who sets the number this round
int setter = (round % 2 == 1) ? 1 : 2;
int guesser = (setter == 1) ? 2 : 1;
printf("%s, please set the secret number (1-100): ", 
setter == 1 ? player1 : player2);
// Get secret number (with simple masking)
scanf("%d", &secretNumber);
// Clear screen to hide the number
clearScreen();
printf("Number set! %s, start guessing!\n\n", 
guesser == 1 ? player1 : player2);
// Guessing phase
int attempts = 0;
int maxAttempts = 7;
int found = 0;
while (attempts < maxAttempts && !found) {
printf("Attempt %d/%d - Enter your guess: ", 
attempts + 1, maxAttempts);
scanf("%d", &guess);
attempts++;
if (guess < secretNumber) {
printf("   Too low!\n");
} else if (guess > secretNumber) {
printf("   Too high!\n");
} else {
printf("\nπŸŽ‰ CORRECT! πŸŽ‰\n");
printf("%s guessed it in %d attempts!\n", 
guesser == 1 ? player1 : player2, attempts);
// Score: more points for fewer attempts
int points = (maxAttempts - attempts + 1) * 10;
scores[guesser] += points;
printf("Points earned: %d\n", points);
found = 1;
}
}
if (!found) {
printf("\nOut of attempts! The number was %d.\n", secretNumber);
}
// Show current scores
printf("\n--- Current Scores ---\n");
printf("%s: %d points\n", player1, scores[1]);
printf("%s: %d points\n", player2, scores[2]);
printf("Press Enter to continue...");
while (getchar() != '\n');
getchar();
}
// Game over - show winner
clearScreen();
printf("\n========================================\n");
printf("           GAME OVER\n");
printf("========================================\n");
printf("Final Scores:\n");
printf("%s: %d points\n", player1, scores[1]);
printf("%s: %d points\n", player2, scores[2]);
if (scores[1] > scores[2]) {
printf("\nπŸ† %s WINS! πŸ†\n", player1);
} else if (scores[2] > scores[1]) {
printf("\nπŸ† %s WINS! πŸ†\n", player2);
} else {
printf("\n🀝 IT'S A TIE! 🀝\n");
}
return 0;
}

Key Concepts Explained

1. Random Number Generation

#include <stdlib.h>
#include <time.h>
// Seed the random generator (do this once at program start)
srand(time(NULL));
// Generate random number between 1 and 100
int secretNumber = rand() % 100 + 1;

2. Input Validation

// Check if input is valid
if (scanf("%d", &guess) != 1) {
printf("Invalid input! Please enter a number.\n");
while (getchar() != '\n'); // Clear input buffer
continue;
}

3. Game Loop Structure

do {
// Get player guess
// Check if correct
// Provide feedback
} while (guess != secretNumber && attempts < maxAttempts);

4. Score Calculation

// Simple scoring based on attempts
int score = 100 - (attempts * 10);
if (score < 0) score = 0;

Common Enhancements to Try

  1. Difficulty Levels: Add easy, medium, and hard modes
  2. Score Persistence: Save high scores to a file
  3. Timed Mode: Add a timer to limit guessing time
  4. Hint System: Provide hints after certain attempts
  5. Multiplayer: Allow two players to compete
  6. Range Customization: Let players set their own range
  7. Statistics: Track average attempts, win rate, etc.

Compilation and Running

# Compile the game
gcc -o guessing_game guessing_game.c
# Run the game
./guessing_game
# For Windows (if using MinGW)
gcc -o guessing_game.exe guessing_game.c
guessing_game.exe

Conclusion

The number guessing game is an excellent project for beginning C programmers. It demonstrates:

  • Random number generation with rand() and srand()
  • User input with scanf()
  • Conditional logic with if-else statements
  • Loops with while and do-while
  • Input validation and buffer clearing
  • Game state management with variables
  • Program structure and function organization

From a simple 20-line program to a fully-featured game with difficulty levels, scoring, and multiplayer support, this project scales well with your learning. Start with the basic version and gradually add features as you become more comfortable with C programming concepts.

Leave a Reply

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


Macro Nepal Helper