We've seen all those tutorials about calculators n all which show how to add and stuff, example;
int x = 4; int y = 5; int result = x + y; Console.WriteLine("Total Sum is : {0}", result);
So fireup your visual studio create a new console application, if you dunno how to read,
How to create new console app. in C#.
1. Ask for user input whether he/she wants to add or multiply, and store input in "choice
Console.Write("Enter 1 for addition, 2 for multiplication: "); int choice = int.Parse(Console.ReadLine());
class SimpleCalculator{ }3. Now lets make two methods for add and multiply
public int add(int x, int y) { Console.Write("\nThe addition is "); return x + y; }
public int mul(int x, int y) { Console.Write("\nThe multiplication is "); return x * y; }
4. Full code for main method:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.Write("Enter 1 for addition, 2 for multiplication: "); int choice = int.Parse(Console.ReadLine()); if (choice == 1) { //addition Console.WriteLine("Welcome to Addition..."); Console.WriteLine("\nEnter first number: "); int num1 = int.Parse(Console.ReadLine()); Console.WriteLine("\nEnter second number: "); int num2 = int.Parse(Console.ReadLine()); SimpleCalculator AddCalc = new SimpleCalculator(); Console.WriteLine(AddCalc.add(num1, num2)); } else if (choice == 2) { Console.WriteLine("Welcome to Multiplication..."); Console.WriteLine("\nEnter first number: "); int num1 = int.Parse(Console.ReadLine()); Console.WriteLine("\nEnter second number: "); int num2 = int.Parse(Console.ReadLine()); SimpleCalculator Mul = new SimpleCalculator(); Console.WriteLine(Mul.mul(num1, num2)); } Console.ReadLine(); } } }5. Full code for SimpleCalculator class:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class SimpleCalculator { public int add(int x, int y) { Console.Write("\nThe addition is "); return x + y; } public int mul(int x, int y) { Console.Write("\nThe multiplication is "); return x * y; } } }
No comments:
Post a Comment