C# Example: accepting user input and performing a calculation - Biz Tech

C# Example: accepting user input and performing a calculation

Listen
 using System;

class Program
{
    static void Main(string[] args)
    {
        Console.Write("Enter the first number: ");
        string input1 = Console.ReadLine();

        Console.Write("Enter the second number: ");
        string input2 = Console.ReadLine();

        if (!int.TryParse(input1, out int number1) || !int.TryParse(input2, out int number2))
        {
            Console.WriteLine("Invalid input.");
            return;
        }

        int result = number1 + number2;
        Console.WriteLine("The result is " + result + ".");
    }
}

This example prompts the user to enter two numbers, performs validation using int.TryParse(), and then performs a calculation and outputs the result. The following steps are performed:

  1. Prompt the user to enter the first number using Console.Write() and read the input using Console.ReadLine().
  2. Prompt the user to enter the second number using Console.Write() and read the input using Console.ReadLine().
  3. Use int.TryParse() to attempt to parse the input strings as integers. If parsing fails, output an error message and return from the method using the return keyword.
  4. Perform the calculation using the input numbers.
  5. Output the result to the console using Console.WriteLine().