So I have been playing around with C# lately and I don't understand output formatting.
using System;
namespace Arrays
{
class Program
{
static void Main()
{
Random r = new Random();
int[] Numbers = new int[10];
for (int i = 0; i < Numbers.Length; i++)
{
Numbers[i] = r.Next(101);
}
for (int i = 0; i < Numbers.Length; i++)
{
Console.WriteLine("index {0} holds number {0}", i,Numbers[i]);
}
}
}
}
Output
My expected output was index i holds number Number[i]
. So can anyone explain what to change, or link me with a good C# page on output formatting topic.
I know there is a way to do it in 2 lines.
Change
Console.WriteLine("index {0} holds number {0}", i, Numbers[i]);
to
Console.WriteLine("index {0} holds number {1}", i, Numbers[i]);
Reason: Your indices (in the format string) reference the parameters after the string in zero-based index order. So {0} for the first parameter after the string, {1} for the second, {2} if you have a third etc.
See this page for more info.
edit: You can reference the parameters multiple times in your format String, too. E.g.:
Console.WriteLine(
"index {0} holds number {1} (Numbers[{0}] == {1})", i, Numbers[i]);
This also is equivalent to
Console.WriteLine(String.Format(
"index {0} holds number {1} (Numbers[{0}] == {1})", i, Numbers[i]));
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