Sunday 7 March 2010

Simple Arithmetic Calculator using C#

Simple Arithmetic calculator in C# using Switch case

The following is the code for creating a simple arithmetic calculator using switch case:

what is a switch case?

Switch case helps the programmer to provide multiple conditions when multiple options are required to be provided
.

Syntax:

switch(variablename)
{
case expression1:
statement;
break;
case expression2:
statement;
break;
.
.
.
default:
statement;
break;
}


The Program for simple arithmetic calculator is as follows:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class maths
{
static void Main(string[] args)
{
// float datatype chosen for decimal calculation.
float a, b;
// character datatype chosen to provide option for-
// switch case.
char option;

Console.WriteLine("Enter the numbers to be calculated");
// first value to be provided by the programmer.
a = Convert.ToInt32(Console.ReadLine());
// second value to be provided by the programmer.
b = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter the option");
Console.WriteLine("Enter a to add");
Console.WriteLine("Enter b to subtract");
Console.WriteLine("Enter c to multiply");
Console.WriteLine("Enter d to Divide");
// option to be inserted by the programmer.
option = Convert.ToChar(Console.ReadLine());
// switch case
switch (option)
{
// various options of switchcase(a,b,c,d)
case 'a':
Console.WriteLine("the sum is{0}:", a + b);
break;
case 'b':
Console.WriteLine("the difference is{0}:", b - a);
break;
case 'c':
Console.WriteLine("the product is{0}:", a * b);
break;
case 'd':
Console.WriteLine("the divided output is {0}:", a / b);
break;
// default option.
default:
Console.WriteLine("invalid choice");
break;
}

}
}
}


No comments:

Post a Comment