C Programming: Number Guessing Game Tutorial – Complete Guide with Source Code
The number guessing game is a perfect beginner project in C programming that teaches essential concepts like random number generation, loops, conditional statements, and user input handling. This comprehensive tutorial includes multiple versions from basic to advanced implementations.
What You’ll Learn
- Random number generation using srand() and rand()
- Game loops and user interaction patterns
- Conditional logic and decision making
- Input validation and error handling
- Building interactive console applications
Basic Number Guessing Game
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int secretNumber, userGuess, attempts = 0;
// Initialize random seed
srand(time(NULL));
// Generate random number between 1 and 100
secretNumber = rand() % 100 + 1;
printf("==========================================\n");
printf(" 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");
do {
printf("Enter your guess: ");
scanf("%d", &userGuess);
attempts++;
if (userGuess < secretNumber) {
printf("Too low! Try again.\n\n");
} else if (userGuess > secretNumber) {
printf("Too high! Try again.\n\n");
} else {
printf("\nCongratulations! You guessed it!\n");
printf("The number was %d\n", secretNumber);
printf("You took %d attempts.\n", attempts);
// Performance evaluation
if (attempts <= 3) {
printf("Excellent! You're a guessing master!\n");
} else if (attempts <= 6) {
printf("Good job! Nice guessing skills!\n");
} else if (attempts <= 10) {
printf("Not bad! You got there in the end!\n");
} else {
printf("You made it! Practice makes perfect!\n");
}
}
} while (userGuess != secretNumber);
return 0;
}
Enhanced Version with Difficulty Levels
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int playGame(int maxNumber, int maxAttempts) {
int secretNumber, userGuess, attempts = 0;
secretNumber = rand() % maxNumber + 1;
printf("\nI'm thinking of a number between 1 and %d.\n", maxNumber);
if (maxAttempts > 0) {
printf("You have %d attempts to guess it!\n\n", maxAttempts);
} else {
printf("You have unlimited attempts!\n\n");
}
do {
printf("Attempt %d: Enter your guess: ", attempts + 1);
scanf("%d", &userGuess);
attempts++;
if (userGuess < secretNumber) {
printf("Too low!");
if (maxAttempts > 0) {
printf(" (%d attempts remaining)", maxAttempts - attempts);
}
printf("\n");
} else if (userGuess > secretNumber) {
printf("Too high!");
if (maxAttempts > 0) {
printf(" (%d attempts remaining)", maxAttempts - attempts);
}
printf("\n");
} else {
printf("\nCONGRATULATIONS!\n");
printf("You guessed the number %d correctly!\n", secretNumber);
printf("It took you %d attempts.\n", attempts);
return 1; // Success
}
// Check if max attempts reached
if (maxAttempts > 0 && attempts >= maxAttempts) {
printf("\nGAME OVER!\n");
printf("You've used all %d attempts.\n", maxAttempts);
printf("The number was %d.\n", secretNumber);
return 0; // Failure
}
} while (userGuess != secretNumber);
return 1;
}
int main() {
int choice;
char playAgain;
srand(time(NULL));
printf("==========================================\n");
printf(" ADVANCED NUMBER GUESSING GAME \n");
printf("==========================================\n");
do {
printf("\nSelect difficulty level:\n");
printf("1. Easy (1-50, unlimited attempts)\n");
printf("2. Medium (1-100, 10 attempts)\n");
printf("3. Hard (1-500, 8 attempts)\n");
printf("4. Expert (1-1000, 6 attempts)\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("\n=== EASY MODE ===");
playGame(50, 0);
break;
case 2:
printf("\n=== MEDIUM MODE ===");
playGame(100, 10);
break;
case 3:
printf("\n=== HARD MODE ===");
playGame(500, 8);
break;
case 4:
printf("\n=== EXPERT MODE ===");
playGame(1000, 6);
break;
default:
printf("Invalid choice! Please try again.\n");
continue;
}
printf("\nWould you like to play again? (y/n): ");
scanf(" %c", &playAgain);
} while (playAgain == 'y' || playAgain == 'Y');
printf("Thanks for playing! Goodbye!\n");
return 0;
}
Version with Hints and Statistics
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
typedef struct {
int gamesPlayed;
int gamesWon;
int totalAttempts;
int bestScore;
} GameStats;
void displayStats(GameStats stats) {
printf("\n=== YOUR STATISTICS ===\n");
printf("Games Played: %d\n", stats.gamesPlayed);
printf("Games Won: %d\n", stats.gamesWon);
if (stats.gamesPlayed > 0) {
printf("Win Rate: %.1f%%\n", (float)stats.gamesWon / stats.gamesPlayed * 100);
}
if (stats.gamesWon > 0) {
printf("Average Attempts: %.1f\n", (float)stats.totalAttempts / stats.gamesWon);
printf("Best Score: %d attempts\n", stats.bestScore);
}
printf("======================\n");
}
int playGameWithHints() {
int secretNumber, userGuess, attempts = 0;
int lower = 1, upper = 100;
char wantHint;
secretNumber = rand() % 100 + 1;
printf("\n=== GAME WITH HINTS ===\n");
printf("I'm thinking of a number between 1 and 100.\n");
printf("You can ask for hints after 3 attempts!\n\n");
do {
printf("Range: %d to %d\n", lower, upper);
printf("Attempt %d: Enter your guess: ", attempts + 1);
scanf("%d", &userGuess);
attempts++;
if (userGuess < secretNumber) {
printf("Too low!\n");
if (userGuess >= lower) {
lower = userGuess + 1;
}
} else if (userGuess > secretNumber) {
printf("Too high!\n");
if (userGuess <= upper) {
upper = userGuess - 1;
}
} else {
printf("\nPERFECT! You found it!\n");
printf("The number was %d\n", secretNumber);
printf("You needed %d attempts.\n", attempts);
return attempts;
}
// Offer hint after 3 attempts
if (attempts >= 3 && attempts % 2 == 1) {
printf("Would you like a hint? (y/n): ");
scanf(" %c", &wantHint);
if (wantHint == 'y' || wantHint == 'Y') {
if (secretNumber % 2 == 0) {
printf("Hint: The number is EVEN.\n");
} else {
printf("Hint: The number is ODD.\n");
}
if (attempts >= 5) {
int digitSum = 0;
int temp = secretNumber;
while (temp > 0) {
digitSum += temp % 10;
temp /= 10;
}
printf("Bonus hint: Sum of digits is %d.\n", digitSum);
}
}
}
printf("\n");
} while (userGuess != secretNumber);
return attempts;
}
int main() {
GameStats stats = {0, 0, 0, 0};
int choice, attempts;
char playerName[50];
srand(time(NULL));
printf("==========================================\n");
printf(" NUMBER GUESSING GAME WITH HINTS \n");
printf("==========================================\n");
printf("Enter your name: ");
fgets(playerName, sizeof(playerName), stdin);
playerName[strcspn(playerName, "\n")] = 0; // Remove newline
printf("Hello %s! Welcome to the guessing game!\n", playerName);
do {
printf("\n=== MAIN MENU ===\n");
printf("1. Play Game\n");
printf("2. View Statistics\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
stats.gamesPlayed++;
attempts = playGameWithHints();
stats.gamesWon++;
stats.totalAttempts += attempts;
if (stats.bestScore == 0 || attempts < stats.bestScore) {
stats.bestScore = attempts;
printf("NEW BEST SCORE!\n");
}
// Performance feedback
if (attempts <= 5) {
printf("Outstanding performance!\n");
} else if (attempts <= 8) {
printf("Great job!\n");
} else if (attempts <= 12) {
printf("Good effort!\n");
} else {
printf("Keep practicing!\n");
}
break;
case 2:
displayStats(stats);
break;
case 3:
printf("\nThanks for playing, %s!\n", playerName);
displayStats(stats);
printf("Goodbye!\n");
break;
default:
printf("Invalid choice! Please try again.\n");
}
} while (choice != 3);
return 0;
}
Key Programming Concepts
Random Number Generation: The programs use srand(time(NULL))
for seeding and rand()
for generating random numbers within specific ranges.
Control Structures: Various loop types including do-while
and while
loops demonstrate different approaches to game flow control.
Function Design: The advanced versions show how to organize code into reusable functions for better maintainability.
Data Structures: The statistics version uses structures to organize related game data efficiently.
Compilation and Usage
# Compile any version
gcc guessing_game.c -o guessing_game
# Run the program
./guessing_game
Practice Exercises
- Add a two-player mode where players take turns
- Implement a time limit for each guess
- Create custom difficulty with user-defined ranges
- Add file saving for persistent high scores
- Build a graphical progress indicator
Conclusion
The number guessing game is an excellent introduction to C programming fundamentals. It combines essential concepts like random number generation, loops, conditionals, and user interaction in an engaging format. These examples demonstrate progressive complexity from basic implementations to feature-rich applications with statistics tracking and hint systems.