C# Programing
Fundamentals
Fundamentals
  • C# Fundamental concepts
    • Introduction to C#.NET
    • Variables and Types
    • User Input
    • Strings
    • Methods
    • Date and Time
    • Conditions
    • Loops
    • Arrays
  • Problem based learning
    • P1: Arithmetic Calculator
    • P2: Number Guessing
    • P3: Print Patterns
    • P4: Grade Average
    • P5: Calculate Age
  • Practice Problems
    • W3Schools
    • Edabit
Powered by GitBook
On this page
  1. Problem based learning

P2: Number Guessing

Program 2: Number Guessing Game

This program introduces loops and more complex conditionals. It's a simple game where the user has to guess a randomly generated number.

Random random = new Random();
int randomNumber = random.Next(1, 101); // Random number between 1 and 100
int attempts = 0;
int userGuess = 0;

Console.WriteLine("Guess the number (1-100)!");

while (userGuess != randomNumber)
{
    Console.Write("Enter your guess: ");
    userGuess = Convert.ToInt32(Console.ReadLine());
    attempts++;

    if (userGuess < randomNumber)
    {
        Console.WriteLine("Too low, try again.");
    }
    else if (userGuess > randomNumber)
    {
        Console.WriteLine("Too high, try again.");
    }
}

Console.WriteLine($"Congratulations! You guessed the number in {attempts} attempts.");
PreviousP1: Arithmetic CalculatorNextP3: Print Patterns

Last updated 1 year ago