C# Cognizant Handson Solutions

CalculatorProgram C# Cognizant Handson Solution

Create a class called Calculator which contains methods for arithmetic operations such as Addition, Subtraction ,Multiplication and Division. Division method should return the Quotient and Remainder(hint:use out parameter).

Follow the method signatures as given below:

public int Addition(int a, int b)

public int Subtraction(int a, int b)

public int Multiplication(int a, int b)

public double Division(int a, int b, out double remainder).  //The method should  return the Quotient and Remainder  should be  passed through the out parameter.

The methods should return the appropriate result.

Create a class Program with Main Method . Prompt for 2 operands and operator from the user, Call the appropriate method for operation and display the results.

Note:

Don’t create any new namespace.

Create classes with pubic access specifier

Sample Input

Enter the operator

+

Enter the operands

12

10

Sample Output

Result of 12 + 10 is 22

Sample Input

Enter the operator

/

Enter the operands

11

2

Sample Output

Result of 11 / 2 is 5

Remainder =1

Sample Input

Enter the operator

&

Enter the operands

12

10

Sample Output

Invalid Operator

CalculatorProgram.cs

using System;

public class Calculator
{
    public int Addition(int a, int b)
    {
        return a + b;
    }

    public int Subtraction(int a, int b)
    {
        return a - b;
    }

    public int Multiplication(int a, int b)
    {
        return a * b;
    }

    public double Division(int a, int b, out double remainder)
    {
        remainder = a % b;
        return Convert.ToInt32(a / b);
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        Calculator c = new Calculator();

        Console.WriteLine("Enter the operator");
        char op = Console.ReadLine()[0];

        Console.WriteLine("Enter the operands");
        int num1 = int.Parse(Console.ReadLine());
        int num2 = int.Parse(Console.ReadLine());

        switch (op)
        {
            case '+':
                Console.WriteLine("Result of {0} {1} {2} is {3}", num1, op, num2, c.Addition(num1, num2));
                break;
            case '-':
                Console.WriteLine("Result of {0} {1} {2} is {3}", num1, op, num2, c.Subtraction(num1, num2));
                break;
            case '*':
                Console.WriteLine("Result of {0} {1} {2} is {3}", num1, op, num2, c.Multiplication(num1, num2));
                break;
            case '/':
                double remainder;
                Console.WriteLine("Result of {0} {1} {2} is {3}\nRemainder = {4}", num1, op, num2, c.Division(num1, num2, out remainder), remainder);
                break;
            default:
                Console.WriteLine("Invalid Operator");
                break;
        }
    }
}

Similar Posts