total sum of 2d array values c# - 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();
}

Related

How can I close this for loop 2d array in 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]);
}

Count the number of occurrences in an array with random numbers without methods or list in C#

I am trying to solve an exercise in C# as follows:
Write a program that generates 20 random integers between 0 and 9 and displays the count for each number.
Use an array of ten integers, say counts, to store the counts for the number of 0s, 1s, ..., 9s.)
This is what i come up with which kind of work but i have a problem with the 0's counting 1 extra all the time.
using System.Collections.Generic;
using System.Text;
namespace ArrayExercises
{
class TaskFive
{
public static void FindNumberCount()
{
int c0=0,c1=02,c2=0,c3=0,c4=0,c5=0,c6=0,c7=0,c8=0,c9=0;
int[] arr = new int[20];
Random rand = new Random();
Console.WriteLine("Numbers generated ");
for (int i = 0; i < 19; i++)
{
arr[i] = rand.Next(0, 10);
Console.WriteLine(arr[i]);
}
foreach(int number in arr)
{
if (number == 0) { c0++; }
else if (number == 1) { c1++; }
else if (number == 2) { c2++; }
else if (number == 3) { c3++; }
else if (number == 4) { c4++; }
else if (number == 5) { c5++; }
else if (number == 6) { c6++; }
else if (number == 7) { c7++; }
else if (number == 8) { c8++; }
else if (number == 9) { c9++; }
}
Console.WriteLine
(
$"Number of 0's: {c0} \n" +
$"Number of 1's: {c1} \n" +
$"Number of 2's: {c2} \n" +
$"Number of 3's: {c3} \n" +
$"Number of 4's: {c4} \n" +
$"Number of 5's: {c5} \n" +
$"Number of 6's: {c6} \n" +
$"Number of 7's: {c7} \n" +
$"Number of 8's: {c8} \n" +
$"Number of 9's: {c9}"
);
}
}
}
Thanks in advance :)
You could shorten it like this
public static void FindNumberCount()
{
int[] count = new int[10];
Random rand = new Random();
int[] arr = new int[20];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = rand.Next(0, 10);
Console.WriteLine(arr[i]);
count[arr[i]]++;
}
for (int i = 0; i < count.Length; i++)
{
Console.WriteLine($"Number of {i}'s: {count[i]}");
}
}
If you want draw 20 numbers you should for (int i = 0; i < 20; i++) not 19.
int[] counts = new int[10];
int[] numbers = new int[20];
var random = new Random();
for (int i = 0; i < numbers.Length; i++)
{
// Generate random numbers
numbers[i] = random.Next(0, 9);
// Increment the count of the generated number
counts[numbers[i]]++;
}
the for loop you use loops only 19 times.
You must change the "i < 19" to "i < 20".
In your program, the for loop leaves the last int in the array at it's default value (0),
this also explains, why you always have one more zero.
Hope this helped.
The issues is in this line
for (int i = 0; i < 19; i++)
You initialized an array with 20 int and set only value to 19 of them.
If you don't set the value int defaults to Zero and hence you always get one extra zero
Change your code as below
for (int i = 0; i <= 19; i++)
The halting condition of the first for loop should be i<20. Then your program should work.
This is how I would solve it:
static void Main(string[] args)
{
Random random = new Random();
//Fill array with random numbers
int[] array = new int[20];
for (int i = 0; i < array.Length; i++)
array[i] = random.Next(0, 10);
//Count how many times a number occurs
int[] numberCounts = new int[10];
for (int i = 0; i < array.Length; i++)
numberCounts[array[i]]++;
//Print the count of the numbers
for(int i = 0; i < numberCounts.Length; i++)
Console.WriteLine("Number of " + i + "'s: " + numberCounts[i]);
//Keep the console open
Console.ReadLine();
}

Bubble sorting issues

Im currently writing code to sort an array through bubble sort. I've previously written it using a set array that i created and it worked perfectly. However, i tried to change it to a randomly generated array and its now broken. wondered if anyone could give me a hand. thanks in advance.
using System;
namespace BubbleSot_Fin
{
class Program
{
static void Main(string[] args)
{
int N = 5;
int m = 100;
int i = 1; //n = number of values m = max value in array
Random Rand = new Random();
int[] array = new int[N + 1];
for ( i = 1; i <= N; i++)
{
array[i] = Rand.Next(1, m); //Randomise the array
Console.WriteLine("This is the unsorted array");
Console.WriteLine("");
for (i = 0; i < array.Length; i++)
{
Console.WriteLine("A[" + i + "] = " + array[i] ); // shows the unsorted numbers
}
int[] Bubble = BubbleSort(array);
Console.WriteLine("");
Console.WriteLine("Array after Bubble Sort");
Console.WriteLine("");
for ( i = 0; i < Bubble.Length; i++)
{
Console.WriteLine("A[" + i + "] = " + Bubble[i]); // shows the numbers after sorting
}
Console.ReadLine();
}
private static int[] BubbleSort(int[] BSArray)
{
int length = array.Length;
for ( i = 0; i < length - 1; i++)
{
for (int j = 0; j < length - 1 - i; j++)
{
if (array[j] > array[j + 1])
{
int number = array[j];
array[j] = array[j + 1];
array[j + 1] = number;
}
}
}
return BSArray;
}
}
}
The errors i'm having are that the private and static word for the bubble sort are incorrect.
The errors are :
- CS0106 The modifier 'Private' is not valid for this item
- CS0106 The modifier 'Static' is not valid for this item

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.

Categories

Resources