Program 1: Basic Arithmetic Calculator
This program introduces variables, basic data types, input/output, and simple conditionals. It performs arithmetic operations based on user input.
using System;
class BasicCalculator
{
static void Main()
{
Console.Write("Enter the first number: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the second number: ");
int num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter operation (+, -, *, /): ");
char operation = Console.ReadKey().KeyChar;
Console.WriteLine();
int result;
switch (operation)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
Console.WriteLine("Invalid operation.");
return;
}
Console.WriteLine($"Result: {num1} {operation} {num2} = {result}");
}
}
Using modern and simplified features of C#
Console.Write("Enter the first number: ");
var num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the second number: ");
var num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter operation (+, -, *, /): ");
var operation = Console.ReadKey().KeyChar;
Console.WriteLine();
var result = operation switch
{
'+' => num1 + num2,
'-' => num1 - num2,
'*' => num1 * num2,
'/' => num1 / num2,
_ => throw new InvalidOperationException("Invalid operation.")
};
Console.WriteLine($"Result: {num1} {operation} {num2} = {result}");