Lab-10
Q.1) You need to perform Arithmetic operations on two numbers. The operations include Add Numbers, Multiply Numbers, Divide Numbers, Subtract Numbers and Find Max Number.
Task 1: Define a class ArithmeticOperation having the above methods.
Task 2: Define a Delegate which can call these methods.
Task 3: Create a console application to accept two numbers and arithmetic operation to be performed from the user. Based on the choice, the Delegate instance will hold the address of the appropriate method.
Task 4: Execute the delegate to get the required result.
using System;
namespace ArithmeticOperation
{
class Program
{
private delegate double Operation(double num1, double num2);
private static void Main(string[] args)
{
Console.Write("Input number 1: ");
var num1 = double.Parse(Console.ReadLine());
Console.Write("Input number 2: ");
var num2 = double.Parse(Console.ReadLine());
Console.Write("Input operation (+,*,/,- or max): ");
var op = Console.ReadLine().Trim();
Operation operation;
switch (op)
{
case "+":
operation = ArithmeticOperation.AddNumbers;
break;
case "*":
operation = ArithmeticOperation.MultiplyNumbers;
break;
case "/":
operation = ArithmeticOperation.DivideNumbers;
break;
case "-":
operation = ArithmeticOperation.SubtractNumbers;
break;
case "max":
operation = ArithmeticOperation.FindMaxNumber;
break;
default:
Console.WriteLine("Error: operation is no supported");
return;
}
var result = operation(num1, num2);
Console.WriteLine($"Result: {result}");
}
}
public class ArithmeticOperation
{
public static double AddNumbers(double num1, double num2) => num1 + num2;
public static double MultiplyNumbers(double num1, double num2) => num1 * num2;
public static double DivideNumbers(double num1, double num2) => num1 / num2;
public static double SubtractNumbers(double num1, double num2) => num1 - num2;
public static double FindMaxNumber(double num1, double num2) => num1 >= num2 ? num1 : num2;
}
}
Comments
Leave a comment