C
  • Introduction
    • Fundamentals of a Program
    • Overview of C
    • Features of C
  • Installing Required Software
    • Setting Up VSCode for Windows
    • Setting Up VSCode for macOS
    • Setting Up VSCode for Ubuntu
  • Starting to write code
    • Compiling and Running Your Code
    • Creating Our First C Program
    • Errors and Warnings
    • Program: Writing a C Program to Display Your Name
    • Structure of a C Program
  • Basic Concepts
    • Comments in C
    • Preprocessor in C
    • The #include Statement
    • Displaying Output
    • Reading Input from the Terminal
    • Enums and Chars
    • Data Types and Variables
    • Format Specifiers
    • Command Line Arguments
    • Program: Calculating the Area of a Triangle
  • Operators
    • Converting Minutes to Years and Days
    • Basic Operators
    • Bitwise Operators
    • Program: Byte Sizes of Basic Data Types
    • cast and sizeof Operators
    • Operator Precedence
  • Control Flow
    • If-Else Statements
    • Program: Weekly Pay Calculation
    • Switch Statement
    • For Loop
    • While and Do-While Loops
    • Nested Loops and Loop Control
    • Program: Guess the Number
  • Arrays
    • Introduction to Arrays
    • Program: Prime Number Generator
    • Multidimensional Arrays
    • Program: simple Weather Program
    • Variable Length Arrays (VLAs)
  • Functions
    • Overview of Functions
    • Defining Functions
    • Arguments and Parameters
    • Returning Data from Functions
    • Variable Scoping
    • Program: Tic Tac Toe Game
    • Recursion
  • Strings
    • Defining a String
    • Constant Strings in C
    • Common String Functions
    • Program: Bubble Sort
    • Searching, Tokenizing, and Analyzing Strings
    • Converting Strings
  • Debugging
    • What is Debugging
    • Understanding the Call Stack
    • Common C Mistakes
    • Understanding Compiler Errors
  • Pointer
    • Defining Pointers
    • Accessing Pointers
    • Program: Pointer Demonstration
    • Pointers and Const
    • Void Pointers
    • String Pointers
    • Array Pointers
    • Utilizing Pointers with Functions
    • Pointer Arithmetic
  • Dynamic Memory Allocation
    • malloc, calloc, and realloc
    • Program: User Input String
    • Memory Deallocation
  • Structure
    • Structures and Arrays
    • Nested Structures
    • Structures and Pointers
    • Structures and Functions
    • Program: Structure pointers and Functions
  • File Input and Output
    • Accessing Files
    • Reading from a File
    • Program: Finding the Total Number of Lines in a Text File
    • Writing to a Text File
    • Finding Your Position in a File
    • Program: Converting Characters in a File to Uppercase
    • Program: Printing the Contents of a File in Reverse Order
  • The Standard C Library
    • Various Functions in C
    • Math Functions in C
    • Utility Functions in C
Powered by GitBook
On this page
  • Algorithm and Pseudocode
  • Ways to Solve the Problem
  • Program

Was this helpful?

  1. Control Flow

Program: Guess the Number

You are tasked with creating a "Guess the Number" C program. The program will generate a random number between 0 and 20, and the user needs to guess this number within five tries. The program should provide feedback on whether the user's guess is too high or too low after each attempt.

Algorithm and Pseudocode

  1. Generate a random number between 0 and 20.

  2. Initialize a variable to count the number of tries, set it to 5.

  3. Display a welcome message and the range of numbers (0 to 20).

  4. Enter a loop that continues until the user guesses the correct number or runs out of tries. a. Prompt the user to enter a guess. b. Check if the guess is correct:

    • If yes, display a congratulatory message and end the loop.

    • If no, provide feedback on whether the guess is too high or too low. c. Decrement the number of tries. d. If the number of tries reaches zero, end the loop and display a message indicating the game is over.

Ways to Solve the Problem

  1. Use a loop and conditional statements to compare the user's guess with the generated number.

  2. Utilize a do-while loop to ensure the user gets at least one chance to guess.

  3. Implement error handling to validate that the user enters numbers within the specified range (0 to 20).

  4. Utilize the rand() function to generate a random number.

Program

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

int main() {
    // Seed the random number generator with the current time
    srand(time(NULL));

    // Generate a random number between 0 and 20
    int secretNumber = rand() % 21;

    // Initialize variables
    int guess;
    int tries = 5;

    // Display welcome message
    printf("This is a guessing game.\n");
    printf("I have chosen a number between 0 and 20 which you must guess.\n");

    // Enter the guessing loop
    do {
        // Display the number of tries left
        printf("\nYou have %d %s.\n", tries, (tries == 1) ? "try left" : "tries left");

        // Prompt the user to enter a guess
        printf("Enter a guess: ");
        scanf("%d", &guess);

        // Validate the guess range
        if (guess < 0 || guess > 20) {
            printf("Invalid guess. Please enter a number between 0 and 20.\n");
            continue;
        }

        // Check if the guess is correct
        if (guess == secretNumber) {
            printf("\nCongratulations. You guessed it!\n");
            break;
        } else {
            // Provide feedback on whether the guess is too high or too low
            printf("Sorry, %d is wrong. My number is %s than that.\n", guess, (guess < secretNumber) ? "greater" : "less");
        }

        // Decrement the number of tries
        tries--;

        // Check if the user has run out of tries
        if (tries == 0) {
            printf("\nGame over. You couldn't guess the number. It was %d.\n", secretNumber);
            break;
        }
    } while (1); // Infinite loop, use 'break' to exit when necessary

    return 0;
}

This C program implements the described "Guess the Number" game with error handling and informative messages for the user. It uses a do-while loop to ensure that the user gets at least one chance to guess and provides feedback on whether the guess is too high or too low. The program also checks for invalid guesses and displays appropriate messages. If the user guesses correctly, a congratulatory message is displayed, and if they run out of tries, the game ends with the correct number revealed.

PreviousNested Loops and Loop ControlNextArrays

Last updated 1 year ago

Was this helpful?