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?
- Learn Core Concepts: Practice variables, input/output, loops, and conditionals.
- Random Number Generation: Understand how to generate unpredictable values.
- User Interaction: Handle real-time user input and provide feedback.
- Game Logic: Implement win/lose conditions and scoring.
- 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
- Difficulty Levels: Add easy, medium, and hard modes
- Score Persistence: Save high scores to a file
- Timed Mode: Add a timer to limit guessing time
- Hint System: Provide hints after certain attempts
- Multiplayer: Allow two players to compete
- Range Customization: Let players set their own range
- 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()andsrand() - User input with
scanf() - Conditional logic with
if-elsestatements - Loops with
whileanddo-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.
Complete C Programming Guide + Compilers Collection
1. C srand() Function – Understanding Seed Initialization
https://macronepal.com/understanding-the-c-srand-function
Explains how srand() initializes the pseudo-random number generator in C by setting a seed value. Using the same seed produces the same sequence, while time(NULL) gives different results each run.
2. C rand() Function Mechanics and Limitations
https://macronepal.com/c-rand-function-mechanics-and-limitations
Explains how rand() generates pseudo-random numbers between 0 and RAND_MAX, its deterministic nature, and limitations for security use cases.
3. C log() Function
https://macronepal.com/c-log-function-2
Covers natural logarithm calculation using <math.h> and its applications.
4. Mastering Date and Time in C
https://macronepal.com/mastering-date-and-time-in-c
Explains <time.h> functions like time(), clock(), difftime(), and struct tm.
5. Mastering time_t Type in C
https://macronepal.com/mastering-the-c-time_t-type-for-time-management
Explains time representation as seconds since Unix epoch and conversion functions.
6. C exp() Function
https://macronepal.com/c-exp-function-mechanics-and-implementation
Explains exponential function exp(x) and its scientific applications.
7. C log() Function (Alternate Guide)
https://macronepal.com/c-log-function
Comparison of log() and log10() with usage examples.
8. C log10() Function
https://macronepal.com/mastering-the-log10-function-in-c
Explains base-10 logarithm for engineering and scientific applications.
9. C tan() Function
https://macronepal.com/understanding-the-c-tan-function
Explains tangent function and radian-based calculations.
10. Random Numbers in C (Secure vs Predictable)
https://macronepal.com/mastering-c-random-numbers-for-secure-and-predictable-applications
Explains difference between rand() and secure randomness methods.
11. Free Online C Compiler
https://macronepal.com/free-online-c-code-compiler-2
Browser-based compiler for testing C programs instantly.
C Functions, Arguments, Parameters & Flow
Mastering Functions in C – Complete Guide
https://macronepal.com/c/mastering-functions-in-c-a-complete-guide/
Covers function structure, modular programming, and real-world usage.
Function Arguments in C
https://macronepal.com/c-function-arguments/
Explains how arguments are passed and used in function calls.
Function Parameters in C
https://macronepal.com/c-function-parameters/
Explains defining inputs for functions and matching them with arguments.
Function Declarations in C
https://macronepal.com/c-function-declarations-syntax-rules-and-best-practices/
Covers prototypes, syntax rules, and best practices.
Function Calls in C
https://macronepal.com/understanding-function-calls-in-c-syntax-mechanics-and-best-practices/
Explains execution flow and parameter handling during function calls.
Void Functions in C
https://macronepal.com/understanding-void-functions-in-c-syntax-patterns-and-best-practices/
Explains functions that do not return values.
Return Values in C
https://macronepal.com/c-return-values-mechanics-types-and-best-practices/
Explains different return types and how functions return results.
Pass-by-Value in C
https://macronepal.com/aws/understanding-pass-by-value-in-c-mechanics-implications-and-best-practices/
Explains how copies of variables are passed into functions.
Pass-by-Reference in C
https://macronepal.com/c/understanding-pass-by-reference-in-c-pointers-semantics-and-safe-practices/
Explains using pointers to modify original variables.
C strstr() Function
https://macronepal.com/aws/c-strstr-function/
Explains substring search inside strings in C.
C Preprocessor & Macros
https://macronepal.com/mastering-c-variadic-macros-for-flexible-debugging/
https://macronepal.com/mastering-the-stdc-macro-in-c/
https://macronepal.com/c-time-macro-mechanics-and-usage/
https://macronepal.com/understanding-the-c-date-macro/
https://macronepal.com/c-file-type/
https://macronepal.com/mastering-c-line-macro-for-debugging-and-diagnostics/
https://macronepal.com/mastering-predefined-macros-in-c/
https://macronepal.com/c-error-directive-mechanics-and-usage/
https://macronepal.com/understanding-the-c-pragma-directive/
https://macronepal.com/c-include-directive/
C Structures, Memory, Scope & Linkage
https://macronepal.com/mastering-structures-in-c/
https://macronepal.com/c-structure-declaration-mechanics-and-usage/
https://macronepal.com/c-structure-initialization-mechanics-and-best-practices/
https://macronepal.com/mastering-c-structure-member-access-for-reliable-data-handling/
https://macronepal.com/c-nested-structures/
https://macronepal.com/mastering-arrays-of-structures-in-c/
https://macronepal.com/c-structure-pointers-mechanics-and-implementation/
https://macronepal.com/understanding-c-structure-parameter-passing-mechanics/
https://macronepal.com/mastering-c-returning-structures-for-efficient-data-flow/
https://macronepal.com/c-self-referential-structures/
https://macronepal.com/mastering-structure-alignment-in-c/
https://macronepal.com/c-structure-padding-mechanics-and-optimization/
https://macronepal.com/understanding-c-flexible-array-members-mechanics-and-usage/
https://macronepal.com/mastering-c-anonymous-structures-for-flattened-data-layouts/
https://macronepal.com/c-unions/
https://macronepal.com/mastering-c-name-mangling-and-symbol-decoration/
https://macronepal.com/c-no-linkage-mechanics-and-scope-isolation/
https://macronepal.com/understanding-c-internal-linkage-mechanics-and-architecture/
C Scope, Storage Classes & Typedef
https://macronepal.com/mastering-function-prototype-scope-in-c/
https://macronepal.com/c-function-scope-mechanics-and-visibility/
https://macronepal.com/understanding-c-file-scope-mechanics-and-architecture/
https://macronepal.com/mastering-c-scope-rules-for-predictable-name-resolution/
https://macronepal.com/c-scope-rules/
https://macronepal.com/mastering-c-register-storage-class-for-historical-context-and-modern-alternatives/
https://macronepal.com/mastering-_thread_local-in-c/
https://macronepal.com/c-extern-storage-class-mechanics-and-usage/
https://macronepal.com/understanding-the-c-static-storage-class-mechanics-and-usage/
https://macronepal.com/c-auto-storage-class/
https://macronepal.com/c-typedef-with-pointers/
Extra Articles
https://macronepal.com/13757-2/
https://macronepal.com/13748-2/
https://macronepal.com/13747-2/
https://macronepal.com/13746-2/
https://macronepal.com/13745-2/
https://macronepal.com/13708-2/
https://macronepal.com/13707-2/
https://macronepal.com/13702-2/
Online Compilers
https://macronepal.com/free-html-online-code-compiler/
https://macronepal.com/free-online-python-code-compiler/
https://macronepal.com/free-online-python2-code-compiler/
https://macronepal.com/free-online-java-code-compiler/
https://macronepal.com/free-online-javascript-code-compiler/
https://macronepal.com/free-online-node-js-code-compiler/
https://macronepal.com/free-online-c-code-compiler/
https://macronepal.com/free-online-c-code-compiler-2/
https://macronepal.com/free-online-c-code-compiler-3/
https://macronepal.com/free-online-php-code-compiler/
https://macronepal.com/free-online-ruby-code-compiler/
https://macronepal.com/free-online-perl-code-compiler/
https://macronepal.com/free-online-lua-code-compiler/
https://macronepal.com/free-online-tcl-code-compiler/
https://macronepal.com/free-online-groovy-code-compiler/
https://macronepal.com/free-online-j-shell-code-compiler/
https://macronepal.com/free-online-haskell-code-compiler/
https://macronepal.com/free-online-scala-code-compiler/
https://macronepal.com/free-online-common-lisp-code-compiler/
https://macronepal.com/free-online-d-code-compiler/
https://macronepal.com/free-online-ada-code-compiler/
https://macronepal.com/free-erlang-code-compiler/
https://macronepal.com/free-online-assembly-code-compiler/
