Can't print index and sum of an array - c#

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

Related

C# WFA - How to make a string list sort in the same positions as a sorted integer list

I am trying to make a high score system for a quiz game I have made. I have got all the scores and their names to read in, sort the scores and put them in rich text boxes (one for scores, one for their names). After I used .Sort() on the integer list (scores), the scores were in the correct order but the names (string list) no longer matched up with the scores.
Here is my code:
public partial class frmhighScore : Form
{
public frmhighScore()
{
InitializeComponent();
this.StartPosition = FormStartPosition.CenterScreen;
this.Name = "High Score";
}
string[] contains;
string[] scorenames;
List<int> scores = new List<int>(){ };
List<string> names = new List<string>(){ };
private void highScore_Load(object sender, EventArgs e)
{
scores.Clear();
names.Clear();
scorenames = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + "scorenames.txt");
foreach (string line in scorenames)
{
gameClass.scorenames.Add(line);
}
for (int x = 0; x < gameClass.scorenames.Count(); x++)
{
contains = gameClass.scorenames[x].Split(':');
names.Add(contains[0]);
scores.Add(Convert.ToInt32(contains[1]));
}
scores.Sort();
scores.Reverse();
for (int a = 0; a < scores.Count; a++)
{
}
for (int y = 0; y < names.Count(); y++)
{
richTextBox1.Text += names[y];
richTextBox1.Text += Environment.NewLine;
}
for (int z = 0; z < scores.Count(); z++)
{
richTextBox2.Text += scores[z];
richTextBox2.Text += Environment.NewLine;
}
}
}
gameClass.scorenames is a string list in my class which is used to read in the details from the text file. All ofther variables are local.
richTextBox1 is for the names and richTextBox2 is for the scores
Here is a screenshot of what the form currently looks like:
Current high score form
And here is the text file that I am reading in from (scorenames.txt):
r:6
bob:10
So as you can see, the names are not matched up with the sorted scores
So my final question is, how would I make it so that the names (bob / r) match up with their scores r is 4, bob is 10?
Any help would be greatly appreciated, thanks.
I think you just need to re model your display entity to bundle both Name and Score together. You might need to change your code somewhat similar to below snippet (I haven't taken care of new line format though)
public class DisplayCard
{
public int Score { get; set; }
public string Name { get; set; }
}
List<DisplayCard> ScoreCard = new List<DisplayCard>();
for (int x = 0; x < gameClass.scorenames.Count(); x++)
{
contains = gameClass.scorenames[x].Split(':');
var name = contains[0];
var score = Convert.ToInt32(contains[1]);
ScoreCard.Add(new DisplayCard { Name = name, Score = score });
}
var sortedCard = ScoreCard.OrderBy(o => o.Score).ToList();
foreach (var card in sortedCard)
{
richTextBox1.Text += card.Name;
richTextBox2.Text += card.Score;
/* take care of new line logic*/
}
You might create objects for each player which includes their score. Then use LINQ to sort them by the score, which will then retain the association with their name: https://msdn.microsoft.com/en-us/library/bb534966.aspx

how to put string into an array C#

i need to put the contents of an text box that is a string into an array.
i have seen lots of people asking how to put each letter as an index in the array but i want the whole string in one index.
for context
i am making an application for a hotel booking for an assignment, it takes a name, room number and length of stay. it also stores room size with radio buttons. then there is another button and a textbox that when you type a room size (Single, double or triple) it will display how many people have book that room type and the name on the booking.
any help would be greatly appreciated. here is what i have done and i picture of what the application is meant to look like.
namespace Assignment2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// MessageBox.Show("Initalize");
}
string[] CusName = new string[150];
int[] RNumber = new int[150];
int[] nights = new int[150];
string[] RSize = new string[150];
string name;
bool blnnumcheck;
bool blnNightsCheck;
private void Form1_Load(object sender, EventArgs e)
{
// MessageBox.Show("Load");
}
private void TxtName_TextChanged(object sender, EventArgs e)
{
name = TxtName.Text;
}
private void btnConfirm_Click(object sender, EventArgs e)
{
string size;
int Roomnum, night;
blnNightsCheck = int.TryParse(txtLengthofStay.Text, out night);
if (!System.Text.RegularExpressions.Regex.IsMatch(TxtName.Text, "([a-zA-Z])"))
{
MessageBox.Show("Invalid Name Please try again");
}
blnnumcheck = int.TryParse(txtRoomNumber.Text, out Roomnum);
if (!blnnumcheck )
{
MessageBox.Show("Invalid Room Number Please try again" );
}
if (Roomnum >= 150)
{
MessageBox.Show("Invalid Room Number Please try again");
}
}
}
}
this what the completed one is supposed to look like
try this:
List<string> myArray = new List<string>();
myArray.Add(myTextBox.Text);
string data = "Hello, Good Morning";
string[] stringArray = new string[]{ data };
Console.WriteLine(stringArray[0]);
If you know how to create arrays, continue reading, if you don't, jump to the content below the horizontal line.
You create an int array using int[], right? So if you want to create a string array, use string[]!
Here is more code:
string[] myArray = new string[10];
//add stuff into the array
myArray[0] = "Hello";
myArray[1] = "World";
//etc
That is simple enough, right? You can do all the things you can do with an int array to a string array.
If you don't know how to create an array, start to read here
You declare an array like this:
type[] array_name = new type[length];
And you can put stuff in the array like this:
array_name[index] = some_stuff;
Thus, you can create an array of strings like this:
string[] myArray = new string[10];
//add stuff into the array
myArray[0] = "Hello";
myArray[1] = "World";
//etc
Just remember, whatever type you want an array to be, write whatever type followed by [] and give it a name!
You can loop through a 2D array like this:
for (int i = 0 ; i < maxX ; i++) { // maxX is the maximum index of the array in the first dimension
for (int j = 0 ; j < maxY ; j++) {
//you can access the array here with array[i][j]
}
}

Textbox to array declaration in C# windows form

Hi I’m fairly new to c# programming so please bear with me. I’m currently working on a “simple” little program which allows the user to enter 25 values into the same text box and once this has been done I want to be able to display this 25 values in a list box as an array of 5 row by 5 column and I want to find out the largest number in the array.
private void button1_Click(object sender, EventArgs e)
{
int arrayrows = 5;
int arraycolomns = 5;
int[,] arraytimes;
arraytimes = new int[array rows, array columns];
// list_Matrix.Items.Add(tb_First.Text);
for (int i = 0; i != 5; i++)
{
for (int j = 0; j != 5; j++)
{
array times [i,j]= Convert. To Int32(Tb_First.Text);
list_Matrix.Items.Add(array times[i, j].To String());
}
}
}
This is what I've tried for displaying the array in a list box, but it isn't working. This also prevents me from moving to the next section of finding the largest number among them.
You can split your string using .Split(' ') (or any other character or string). This will give you a onedimensional array with 25 elements (if everything was entered). The trick to converting that into a twodimensional array or grid is to use integer division and modulo, the following code would to
String[] splitText = textBox.Text.Split(' '); //gets your 25-length 1D array
//make an empty grid with the right dimensions first
int[][] grid = new int[5][];
for (int i=0;i<5;i++) {
grid[i] = new int[5];
}
//save our highest value
int maxVal = 0;
//then fill this grid
for (int i=0;i<splitText.Length;i++){
int value = int.Parse(splitText[i]);
//i%5 gives us values from 0 to 4, which is our 'x-coordinate' in the grid
//i/5 uses integer division so its the same as Math.floor(i/5.0), giving us your 'y-coordinates'
grid[i%5][i/5] = value;
//check if this value is larger than the one that is currently the largest
if (value > maxVal)
{
maxVal = value;
}
}
This will fill the twodimensional grid array with the split textbox text, and if there are not enough values in the textbox it leaves a 0 in those cells.
At the end you will also have your maximum value.
Try the following (shows by printing the numbers as string). and assuming you enter the numbers in the following way,
'1,2,3,4...'
string[] nums=txtBox.Text.Split(',');
lstBox.Items.Clear();
int colCount=5;
int colIndex=0;
string line="";
foreach(string num in nums)
{
if(colIndex==colCount)
{
lstBox.Items.Add(line);
line="";
colIndex=0;
}
line+= line==""? num : " "+num;
colIndex+=1;
}
if(line!="")
lstBox.Items.Add(line);
Make sure to correct any syntax mistakes, and to change the parameter names to yours.
private void button1_Click(object sender, EventArgs e)
{
int[] ab=new int[10];
string s = textBox1.Text;
int j = 0;
string [] a = (s.Split(' '));
foreach (string word in a)
{
ab[j] = Convert.ToInt32(word);
j++;
}
for (int i = 0; i < 10; i++)
{
label2.Text +=ab[i].ToString()+" ";
}
}

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