Answer on Question#39257- Programming, C#
1. For this project, WebSoft Solutions Pvt. Ltd. conducts a recruitment drive to hire 10 software developers to work on various modules of the application. It conducts a written examination and asks the aspiring candidates to create a console-based calculator application. The calculator should be able to solve basic mathematical calculations.
The calculator should store the result of an expression in a variable called "ans", which can be used as an input in other mathematical expressions, as shown in the following statements:
```
<calculate 25*(3+5-(10/2))
ans=75
<calculate ans+10
ans=85
<calculate ans*10/5
```
However, the candidate can declare any variable to store the result. Being an aspiring candidate, develop the console-based calculator using C#.
Solution.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double ans = 0;
private void button1_Click(object sender, EventArgs e)
{
try
{
label1.Text = (sender as Button).Text;
label2.Text = "=";
}
catch { }
}
private void button5_Click(object sender, EventArgs e)
{
double x = 0;
double x1;
double x2;
if (!double.TryParse(textBox1.Text, out x1) || !double.TryParse(textBox2.Text, out x2))
{
label2.Text = "ERROR";
return;
}
else
{
switch (label1.Text[1])
{
case '+':
x = x1 + x2; break;
case '-':
x = x1 - x2; break;
case '*':
x = x1 * x2; break;
case '/':
x = x1 / x2; break;
}
ans = x;
label2.Text = "=" + x;
}
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
char c = e.KeyChar;
char sep = Application.CurrentCulture.NumberFormat.CurrencyDecimalSeparator[0];
switch (c)
{
case '+':
button1_Click(button1, null); break;
case 'x':
case '*':
button1_Click(button3, null); break;
case '-':
button1_Click(button2, null); break;
case '/':
button1_Click(button4, null); break;
case '=':
button5_Click(button5, null); break;
}
e.Handled = !(char.IsDigit(c) || c == sep || c == '-' || c == '\b');
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
label2.Text = "=";
}
private void button6_Click(object sender, EventArgs e)
{
textBox1.Text = ans.ToString();
textBox2.Text = "0";
}
}
}
}