How can I close this for loop 2d array in C#? - c#

I am new to programming I am struggling with how to end this loop.
The teacher is not helping to clarify.
The question I need to answer is "Ask the user to enter five days of the week and rainfall data for each day. Store the data in a two dimensional string array named rainfallData[]" Thanks so much!
String[,] rainFallData = new String[5, 2];
String name;
String rainFall;
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Enter the name of day " + i);
name = Console.ReadLine();
rainFallData[i - 1, 0] = name;
Console.WriteLine("Enter rainFall of day " + i);
rainFall = Console.ReadLine();
rainFallData[i - 1, 1] = rainFall;
for (int row = 0; row < 5; row++)

You can use break. When you want to end the loop just write break;.

Here is a solution that "closes the loop" by only asking for the info 5 times. It also shows how to write the data from the 2d array to the console after.
String[,] rainFallData = new String[5, 2];
for (int i = 0; i < rainFallData.GetLength(0); i++)
{
string name;
string rainFall;
Console.WriteLine("Enter the name of day " + i);
name = Console.ReadLine();
Console.WriteLine("Enter rainFall of day " + i);
rainFall = Console.ReadLine();
rainFallData[i, 0] = name;
rainFallData[i, 1] = rainFall;
}
for (int i = 0; i < rainFallData.GetLength(0); i++)
{
Console.WriteLine("Weekday: " + rainFallData[i,0]);
Console.WriteLine("Rainfall: " + rainFallData[i,1]);
}

Related

User replace value in string array with a new value

Need some help with user input in array. I've created a string array with 5 elements. User types in 5 names and program prints them.
I want the user to type an index and then a new name. Program should print out all the names again but now with the new name instead of the old one on that index.
Console.WriteLine("Type in 5 names: ");
string[] input = new string[5];
for (int i = 0; i < input.Length; i++)
{
input[i] = Console.ReadLine();
}
Console.WriteLine();
for (int i = 0; i < input.Length; i++)
{
int rank = i + 1;
Console.WriteLine(rank + ". " + input[i]);
}
Here I'm suppose to ask user for index (name) to replace, and a name to replace the old one with. But I just can't figure out the code. (I know how to ask but not the code replacing the names).
void Main()
{
Console.WriteLine("Type in 5 names: ");
string[] input = new string[5];
for (int i = 0; i < input.Length; i++)
{
input[i] = Console.ReadLine();
}
Console.WriteLine();
Print(input);
Console.WriteLine("Choose an index: ");
int index = Int32.Parse(Console.ReadLine());
Console.WriteLine("Type new name: ");
string name = Console.ReadLine();
input[index - 1] = name;
Print(input);
}
void Print(string[] names)
{
for (int i = 0; i < names.Length; i++)
{
int rank = i + 1;
Console.WriteLine(rank + ". " + names[i]);
}
}

total sum of 2d array values c#

Hi guys i am trying to create a retrieve method to retrieve a sum total of my 2d array values i have built the array to fill from user input but not sure how to total all array values as i am still learning.
public int[,] ToysMade = new int[4, 5];
public String[] days = new String[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
public void UserInput()
{
String value;
int numCount;
//retrieveing length of ToysMade array dimensions if less than 0 repeat untill last dimension filled
for (int i = 0; i < ToysMade.GetLength(0); i++)
{
for (int ii = 0; ii < ToysMade.GetLength(1); ii++)
{
//taking user input for array dimension 0 "first dimension" then increment it by 1 after input ready for next dimension "i + 1"
value = Microsoft.VisualBasic.Interaction.InputBox("Enter Value For " + days[ii] + " of week " + (i + 1).ToString() + " Enter Value");
try
{
//making sure for only int past through
while (!(int.TryParse(value, out numCount)))
{
MessageBox.Show("Not a valid number, please try again.");
value = Microsoft.VisualBasic.Interaction.InputBox("Enter Value for " + days[i] + " of week " + (i + 1).ToString() + " Enter Value");
}
// taking values enterd from user and set next dimension for next input by incrementing it
ToysMade[i, ii] = numCount;
}
catch (Exception e)
{
MessageBox.Show("Value enterd is not in a valid format");
}
}
}
}
I suggest put either simple foreach loop
int total = 0;
foreach (var item in ToysMade)
total += item;
or nested loops which are typical for 2d arrays
int total = 0;
for (int i = 0; i < ToysMade.GetLength(0); i++)
for (int j = 0; j < ToysMade.GetLength(1); j++)
total += ToysMade[i, j];
You can use Linq by creating an IEnumerable<int>from ToysMade;
var total = ToysMade.Cast<int>().Sum();
Thanks guys awesome works thanks heaps again
public void Sum()
{
int total = 0;
for(int i = 0;i < ToysMade.GetLength(0); i++)
{
for(int j = 0;j < ToysMade.GetLength(1); j++)
{
total += ToysMade[i, j];
}
}
txtOutput.Text += "\r\nThe sum of products is: " + total.ToString();
}

How to get average of columns in a 2d array

I have just started using 2D arrays, but can't seem to figure out how to get the average of each column. I am using a for loop to have the user enter the data( a students grade), then a for loop to display the information user entered. But after the information is displayed, I want to display the average of each column. What should I do get the average of each column?
This is the code I have so far
static void Main(string[] args)
{
double[,] grades = new double[2, 3];
double result;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write("Enter Grade " + (j + 1) + " For Group" + (i + 1) + ": ==>> ");
if (double.TryParse(Console.ReadLine(), out result)) grades[i, j] = result;
else
{
Console.WriteLine("*** INVALID GRADE ENTERED. PLEASE REENTER.");
}
}
}
for (int row = 0; row < 1; row++)
{
Console.WriteLine();
Console.Write(" Group " + (row + 1) + ": ");
Console.WriteLine(" Group " + (row + 2) + ": ");
Console.Write("=========== ===========");
for (int col = 0; col < 3; col++)
{
//String.Format("{0,-10} | {1,-10} | {2,5}",
//make pring for execise 2 Console.Write(string.Format("{0,-5}", grades[row, col]));
Console.WriteLine();
Console.Write(string.Format("{0,-9}", ""));
Console.Write(string.Format("{0,-20}",grades[0, col]));
Console.Write(grades[1,col]);
}
Console.WriteLine();
Console.WriteLine("=========== ===========");
}
Console.WriteLine("\n\npress any key to exit...");
Console.ReadKey();
//print it for exercise 1 myArr[o, column]; myArr[ , column]
}`
If you are looking for a special command that will do it for you, you're out of luck! You'll just have to write the code to do it, the same way you would normally average a series of numbers. Hint: The number of elements in the 'y' dimension of a 2D array is given by e.g. grades.GetLength(1).
To get Average per columns you need to traverse columns for a fixed row and add their values like this:
int columnTotal, average;
for (int row = 0; row < 2; row++)
{
columnTotal = 0;
for (int col = 0; col < 2; col++)
{
columnTotal += grades[row, col];
}
average = columnTotal/2;
Console.WriteLine("Average: {0}", average);
}

How to get an element from list of list

I wrote program and I used in that program a list of lists (in int type).
Every list in the big list stores a different number of integers but when I try to approach those integers and use them for division I don't know how.
That's the program:
Console.WriteLine("How many students in the class?");
int students = int.Parse(Console.ReadLine());
List<List<int>> studentsclass = new List<List<int>>();
for (int i = 0; i < students; i++)
{
Console.WriteLine("How many jumps student number " + (i + 1) + " did?");
int studentjumps = int.Parse(Console.ReadLine());
Console.WriteLine("Write student number " + (i+1) + " high jumps: ");
List<int> jumps= new List<int> (studentjumps);
for (int j = 0; j < studentjumps; j++)
{
jumps.Add(int.Parse(Console.ReadLine()));
}
}
for (int k = 0; k < studentsclass.Count; k++)
{
int sum = 0;
for (int m = 0; m < studentsclass[m].Count; m++)
{
(That is a program that calculates student's average high jumps).
The rest of the code should be: sum = sum\index M of index K of the list.
Edit:
I continued my code and then when it came to the division part I've got lots of errors.
this is what I wrote:
for (int k = 0; k < studentsclass.Count; k++)
{
double sum = 0;
for (int m = 0; m < studentsclass[m].Count; m++)
{
sum = sum + studentsclass[k][m];
}
sum = (double)sum \ studentsclass[m]; \\<-- Error
Console.WriteLine("student number " + (k + 1) + " did an average of " + sum + " meter high jumps");
}
simply use.
studentsclass[k][m]
to access the inner list
and use
studentsclass[k].Count
in your second for loop
Using LINQ you can do somthing like the following to get your desired result:
var result = studentsclass.Select((l, i) => new { Id = i, Average = l.Average() });
See THIS fiddle.

Sort a string array based on an int array without Array.Sort

I need to sort an array of strings based on the array of ints.
I have this to sort my int array
for (int pass = 0; pass < score.Length - ONE; pass++)
{
for (int index = 0; index < score.Length - ONE; index++)
{
if (score[index] > score[index + ONE])
{
int temp = score[index];
score[index] = score[index + ONE];
score[index + 1] = temp;
}
}
}
This int and name array were obtained by
Console.Write("Enter in a name and score: ", i);
userInput = Console.ReadLine();
if (userInput != "")
{
parsedInput = userInput.Split();
name[i] = parsedInput[ZERO];
score[i] = int.Parse(parsedInput[ONE]);
}
For my assignment I need to display the name and their scores organized by the highest score.
I know I could use Array.Sort(score, name) to achieve this but the assignment wants me to not use any of the built in sorting algorithms in the .net library, which is assume Array.Sort would be.
Any tips or help would be greatly appreciated.
You need to rearrange name when you are sorting score so that they are consistent.
for (int pass = 0; pass < score.Length - ONE; pass++)
{
for (int index = 0; index < score.Length - ONE; index++)
{
if (score[index] > score[index + ONE])
{
int temp = score[index];
score[index] = score[index + ONE];
score[index + 1] = temp;
string temp2 = name[index];
name[index] = name[index + ONE];
name[index + 1] = temp2;
}
}
}
When you swap the items in the int array, also swap the corresponding items in the string array. That way the values follow each other, and the name and score remain in sync.
Note that the sorting algorithm is an inefficient version of bubble sort. If there are no swaps in a run of the inner loop, the array is sorted and you can exit out of the outer loop.

Categories

Resources