First time poster here, but I have been using stackoverflow this entire quarter to help me along in my intro to C# class. Generally, I can find what I'm looking for if I look hard enough, but I have been unable to find anyone that has already answered my question.
I have an assignment that wants me to display random numbers in a 5x10 array. I then need to calculate the sum of the numbers and the average, but I'll worry about that later.
Randomized numbers should be <0 and <=100. The console output should look something like this
x x x x x
x x x x x
x x x x x
x x x x x
x x x x x
just with 10 rows instead of 5.
However, my current code is listing the random numbers next to each other and wrapping lines once it reaches the end of the line like this
x x x x x x x x x x x x x x x x x
x x x x x x x x x x x x x x x x x
x x x x ...etc
What can I do to get it to align correctly? I have pretty much exhausted my ability to use format modifiers, so when you see {0, 5}
, that's just my most recent attempt, but far from my only. I'm extremely new to C#, so any advanced techniques would be out of the question, as I wouldn't understand how to properly use them. Any thoughts S.O.?!
using System;
namespace DilleyHW7
{
class Array2d
{
static void Main()
{
const int ROWS = 10;
const int COLS = 5;
const int MAX = 100;
int[,] numbers = new int[10, 5];
Random rand = new Random();
for (int i = 0 ; i< ROWS; ++i)
{
for (int j = 0; j < COLS; ++j)
{
numbers[i, j] = rand.Next(0, 101);
Console.Write(" {0, 5}", numbers[i, j]);
}
}
}
}
}
Hopefully this doesn't screw with the code snippet.... I know I could do some crap like this
int[,] numbers = {
{random.Next(1,100), random.Next(0,100), random.Next(0,100), random.Next(0,100)},
{random.Next(1,100), random.Next(0,100), random.Next(0,100), random.Next(0,100)},
{random.Next(1,100), random.Next(0,100), random.Next(0,100), random.Next(0,100)},
{random.Next(1,100), random.Next(0,100), random.Next(0,100), random.Next(0,100)},
{random.Next(1,100), random.Next(0,100), random.Next(0,100), random.Next(0,100)}
};
but that would get me a very poor score on the assignment.
static void Main()
{
const int ROWS = 10;
const int COLS = 5;
const int MAX = 100;
int[,] numbers = new int[10, 5];
Random rand = new Random();
for (int i = 0 ; i< ROWS; ++i)
{
for (int j = 0; j < COLS; ++j)
{
numbers[i, j] = rand.Next(0, 101);
Console.Write(" {0, 5}", numbers[i, j]);
}
Console.WriteLine("");
}
}
You can use Console.WriteLine() which will insert a line terminator to the end of the input.
You could also use the Environment.EndLine property which will insert the appropriate end of line character.
So your loop would look something like:
for (int j = 0; j < COLS; ++j)
{
numbers[i, j] = rand.Next(0, 101);
Console.Write(" {0, 5}", numbers[i, j]);
}
Console.WriteLine(Environment.EndLine);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With