calculator for binary number system - c#

Can someone write me a calculator that takes two binary numbers and sums them up also multiplies them in C# (windows forms application), please?
i tried this one but it's not working
private void button_Click(object sender, EventArgs e)
{
string[] array = { textBox1.Text, textBox2.Text, textBox3.Text };
label1.Text = GetNumberFormBinary(array);
}
private string GetNumberFormBinary(string[] array)
{
string result = "";
int _base = 2;
for (int i = 0; i < array.Length; i++)
{
int intValue = Convert.ToInt32(array[i], _base);
result += intValue.ToString();
}
return result;
}

As an alternative, you can query array and the result with a help of Linq:
using System.Linq;
...
private static string GetNumberFormBinary(string[] array) => array
.Sum(item => Convert.ToInt32(item, 2))
.ToString();

Related

Can't print index and sum of an array

I have homework. I have to make a program which can input the length of an array with the value in it. After I click the "process" button, the program will make an output of index and value with the result sum and average from the array.
I'm stuck and couldn't print the index and the value to the multiple textbox below process button.
I'm expecting the output will look like this:
Here's the code which I'd been successful write so far:
namespace ArrayProcess
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void process_Click(object sender, EventArgs e)
{
int sum = 0;
string ind = "index";
string message;
int count = Convert.ToInt32(inputArray.Text);
int[] varray = new int[count];
for (int i=1; i <= count; i++)
{
varray[i] = Convert.ToInt32(Interaction.InputBox(message="enter the value of array number "+i));
sum += varray[i];
}
boxSum.Text = Convert.ToString(sum);
}
}
}
Please, help me.
Here is the code for you (boxAvg is for average)
namespace ArrayProcess
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void process_Click(object sender, EventArgs e)
{
int sum = 0;
string ind = "index";
string message;
int count = Convert.ToInt32(inputArray.Text);
int[] varray = new int[count];
for (int i=1; i <= count; i++)
{
varray[i-1] = Convert.ToInt32(Interaction.InputBox(message="enter the value of array number "+i));
sum += varray[i-1];
}
//Refer your list box here to add newly added values to the list
boxSum.Text = Convert.ToString(sum);
boxAvg.Text = Convert.ToString(sum / count); //calculate the average
}
}
}
Given that the array already has data :
private void Display()
{
var columnHeader1 = "Index Value\n";
multilineTextBox1.Text =
columnHeader1 +
string.Join("\n", vArray.Select((x,i)=> $"{i+1,5} {x,5}"));
boxSum.Text = vArray.Sum();
boxAvg.Text = vArray.Average();
var columnHeader2 = "Index Value Histogram\n";
multilineTextBox2.Text =
columnHeader2 +
string.Join("\n", vArray.Select((x,i)=> $"{i+1,5} {x,5} {new String('*', x)}"));
}
String.Join(separator, string[]), To join each row with a Carriage return/Line feed.
.Select((x,i)=> (...), To get each elment of the array an its index.
$"", For the easy string interpolation
{i+1,5}, To display the index i padded on 5 char.
new String('*', x)}, To create a string of N time the same char.
Console demo

Write an array to a file in c#

I am trying to write an array to a file with C# and am having issues.
I've started learning c# the last few days and now can't figure out why this happens.
namespace Arrays
{
class Program
{
static void Sort()
{
}
public static void Random()
{
int[] test2 = new int[5];
int Min = 1;
int Max = 100;
Random randNum = new Random();
for (int i = 0; i < test2.Length; i++)
{
test2[i] = randNum.Next(Min, Max);
Console.WriteLine(test2[i]);
}
Console.WriteLine("");
for (int ii = 0; ii < test2.Length; ii++)
{
Array.Sort(test2);
Console.WriteLine(test2[ii]);
}
String writeToText = string.Format("{0}", test2);
System.IO.File.WriteAllText(#"C:\\Users\\hughesa3\\Desktop\\log.txt", writeToText); // Writes string to text file
}
static void Main(string[] args)
{
Random();
}
}
}
It generates a random 5 numbers and puts it into the array, When I try to write this to a file it prints System.Int32[]
I understand that because im trying to print a formated string but how would i go about printing each int ? I've tried using a loop but it will only save the last int as i put it inside the loop?
Can anyone give me some advice ?
Thanks
Use WriteAllLines and pass string array as input.
System.IO.File.WriteAllLines("filename", test2.Select(i=>i.ToString()).ToArray());
or, if you want to write in , separated form use this.
System.IO.File.WriteAllText("filename", string.Join(",", test2.Select(i=>i.ToString()).ToArray());
The problem is that String writeToText = string.Format("{0}", test2); calls ToString method of the test2 array and it returns System.Int32[]
Change it to
String writeToText = string.Join("", test2.Select(x=>x.ToString())
or
String writeToText = string.Format("{0}", test2.Select(x=>x.ToString().Aggregate((c,n)=>string.Format("{0}{1}", c,n))
//Add this method and use in System.IO.File.WriteAllText(#"C:\\Users\\hughesa3\\Desktop\\log.txt", ArrayToString(test2));
public static String ArrayToString(int[] arr)
{
return arr.Aggregate("", (current, num) => current + (num + " "));
}

Modify sorting algorithm to work with listboxes?

So I'm trying to figure out to modify this integer sorting algorithm to work with data elements (file names) alphabetically in a listbox but have no idea how?
I understand how the sorting algorithm below works and can implement it using an integer array. However, for listBoxes I can't seem to find any relevant examples on the net.
public partial class MainWindow : Window
{
Random rand = new Random();
int numOfIntegers = 1000;
int[] array;
public MainWindow()
{
InitializeComponent();
array = new int[numOfIntegers];
}
// sort a vector of type int using exchange sort
public void ExchangeSort(int[] array)
{
int pass, i, n = array.Length;
int temp;
// make n-1 passes through the data
for (pass = 0; pass < n - 1; pass++)
{
// locate least of array[pass] ... array[n - 1]
// at array[pass]
for (i = pass + 1; i < n; i++)
{
if (array[i] < array[pass])
{
temp = array[pass];
array[pass] = array[i];
array[i] = temp;
}
}
}
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
ExchangeSort(array);
listBox.Items.Clear();
foreach (int i in array)
{
listBox.Items.Add(i);
}
MessageBox.Show("Done");
}
You could try LINQ:
public void sort(int[] array)
{
array = array.OrderByDescending (a => a).ToArray();
}
If I understand correctly, you're trying to sort strings. To compare strings you could simply use the String.CompareTo() method or if you need more than simple comparison, the StringComparator class should do for most use cases.
If you choose to do it this way, the condition while sorting would be something like this:
if (array[i].CompareTo(array[pass]) < 0)
And the rest of the code would probably stay about the same, except of course changing the int[] to String[].
Now, that being said, I would suggest using a List<String> and just skip doing this work by hand altogether. See List.Sort() for reference.
To be a bit more specific, here's an example based on your code of what I mean.
public partial class MainWindow : Window
{
List<String> items;
public MainWindow()
{
InitializeComponent();
items = new List<String>();
// Fill your list with whatever items you need
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
items.Sort();
listBox.Items.Clear();
foreach (String str in items)
{
listBox.Items.Add(str);
}
MessageBox.Show("Done");
}
}

Finding average of the numbers user's type into an array

Could someone please explain to me why my average keeps coming as 0 when I run my program? I have listed the entire code of my project on here and have literally never used arrays before. Also, is the name of this array mData? I tried reading in my book to determine what to look for in these items and have come up with nothing.
public partial class frmMain : Form
{
private const int mSize = 20;
private int[] mData = new int[mSize];
private int mIndex = 0;
private static void Main()
{
frmMain main = new frmMain();
Application.Run(main);
}
private frmMain()
{
InitializeComponent();
}
private void btnEnter_Click(object sender, EventArgs e)
{
int num;
num = int.Parse(txtInput.Text);
//store num in the array
mData[mIndex] = num;
mIndex = mIndex + 1;
//check for full array
if (mIndex == mSize)
{
//inform user that array is full
MessageBox.Show("The array is full.");
btnEnter.Enabled = false;
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Close();
}
private void btnDisplay_Click(object sender, EventArgs e)
{
int n;
for (n = 0; n < mIndex; n++)
listBoxOutput.Items.Add(mData[n]);
}
private void btnAverage_Click(object sender, EventArgs e)
{
int sum = 0;
int average = 0;
if (mIndex == 0)
{
//inform user that array is empty
MessageBox.Show("The array is empty.");
}
//add up the values
for (int i = 0; i < mData.Length; i++)
{
sum += mData[i];
}
//divide by the number of values
average = sum / mSize;
listBoxOutput.Items.Add("The average of the array is: " + average);
}
}
One problem is that you are using ints. If the final value is a decimal less than 1, the int average will store 0. Changing average to a float will solve this. Also, you should not divide by mSize unless you know the entire array is filled. The user could insert one value, but it would be averaged with 19 0s.
since average, sum, and mSize are intergers, when you divide them, the result will be truncated.
average = sum / mSize;
so if sum/mSize is less than 1, average will always be equal to 0
to get average to have decimal points change the declaration to
double average = 0;
and the calculation to
average = (double)sum / (double)mSize;
Array has a built in property to calculate average which returns a decimal value as output. Example is below
int[] integer = new int[] { 1, 2, 3 };
Console.WriteLine(integer.Average().ToString());
Hope this helps.

StreamReader using arraylist or array

Here's my code:
StreamReader reader = new StreamReader("war.txt");
string input = null;
while ((input = reader.ReadLine()) != null)
{
Console.WriteLine(input);
}
reader.Close();
The program above reads and prints out from the file “war.txt” line-by-line. I need to re-write the program so that it prints out in reverse order, i.e., last line first and first line last. For example, if “war.txt” contains the following:
Hello.
How are you?
Thank you.
Goodbye.
The program should prints out:
Goodbye.
Thank you.
How are you?
Hello.
I am very new in C# please help! Thanks!
To do that, you are going to have to buffer the data anyway (unless you do some tricky work with the FileStream API to read the file backwards). How about just:
var lines = File.ReadAllLines("war.txt");
for(int i = lines.Length - 1; i >= 0; i--)
Console.WriteLine(lines[i]);
which just loads the file (in lines) into an array, and then prints the array starting from the end.
A LINQ version of that would be:
foreach(var line in File.ReadLines("war.txt").Reverse())
Console.WriteLine(line);
but frankly the array version is more efficient.
You can do it using recursion with something like this:
void printReverse(int n)
{
String line = reader.readLine();
if (n > 0)
printReverse(n-1);
System.out.println(line);
}
Have a look at adding the lines to a List, then using Reverse on the list and then maybe the ForEach to output the items.
Another option: store each line into a Stack as you read them. After reading the file, pop the stack to print the lines in reverse order.
with the enumerable extension functions, this can be done shorter:
foreach(var l in File.ReadAllLines("war.txt").Reverse())
Console.WriteLine(l);
try
File.ReadAllLines(myFile)
.Reverse();
full code
var list = File.ReadAllLines(filepath).Reverse().ToList();
foreach (var l in list)
Console.WriteLine(l);
Implementation detail
Enumerable.Reverse Method - Inverts the order of the elements in a sequence
File.ReadAllLines Method (String) - Opens a text file, reads all lines of the file, and then closes the file.
here is a example mate, remember to add "using System.IO"
try
{
const int Size = 7;
decimal[] numbers = new decimal[Size];
decimal total = 0m;
int index = 0;
StreamReader inputfile;
inputfile = File.OpenText("Sales.txt");
while (index < numbers.Length && !inputfile.EndOfStream)
{
numbers[index] = decimal.Parse(inputfile.ReadLine());
index++;
}
inputfile.Close();
foreach (decimal Sales in numbers)
{
outputlistBox1.Items.Add(Sales);
total = total + Sales;
}
textBox1.Text = total.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Here is another example from a textbook i bought few years ago, this has highest/lowest/average scores..(remember to use 'using System IO;)
private double Average(int[] iArray)
{
int total = 0;
double Average;
for (int index = 0; index < iArray.Length;
index++)
{
total += iArray[index];
}
Average = (double) total / iArray.Length;
return Average;
}
private int Highest(int[] iArray)
{
int highest = iArray[0];
for (int index = 1; index < iArray.Length; index++)
{
if (iArray[index] > highest)
{
highest = iArray[index];
}
}
return highest;
}
private int Lowest(int[] iArray)
{
int lowest = iArray[0];
for (int index = 1; index < iArray.Length; index++)
{
if (iArray[index] < lowest)
{
lowest = iArray[index];
}
}
return lowest;
}
private void button1_Click(object sender, System.EventArgs e)
{
try
{
const int SIZE = 5;
int[] Scores = new int [SIZE];
int index = 0;
int highestScore;
int lowestScore;
double averageScore;
StreamReader inputFile;
inputFile = File.OpenText("C:\\Users\\Asus\\Desktop\\TestScores.txt");
while (!inputFile.EndOfStream && index < Scores.Length)
{
Scores[index] = int.Parse(inputFile.ReadLine());
index++;
}
inputFile.Close();
foreach (int value in Scores)
{
listBox1.Items.Add(value);
}
highestScore = Highest(Scores);
lowestScore = Lowest(Scores);
averageScore = Average(Scores);
textBox1.Text = highestScore.ToString();
textBox2.Text = lowestScore.ToString();
textBox3.Text = averageScore.ToString("n1");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

Categories

Resources