简体   繁体   中英

Printing out 3 elements in array per line

I have an array with x number of elements and want to print out three elements per line (with a for-loop).

Example:

123    343    3434
342    3455   13355
3444   534    2455

I guess i could use %, but I just can't figure out how to do it.

For loop is more suitable:

var array = Enumerable.Range(0, 11).ToArray();
for (int i = 0; i < array.Length; i++)
{
    Console.Write("{0,-5}", array[i]);
    if (i % 3 == 2)
        Console.WriteLine();
}

Outputs:

0    1    2
3    4    5
6    7    8
9    10   

Loop through the array 3 at a time and use String.Format() .

This should do it...

for (int i = 0; i < array.Length; i += 3)
    Console.WriteLine(String.Format("{0,6} {1,6} {2,6}", array[i], array[i + 1], array[i + 2]));

But if the number of items in the array is not divisable by 3, you'll have to add some logic to make sure you don't go out of bounds on the final loop.

You perhaps need to fix the format spacing...

for(int i=0;i<array.Length;i++)
{
    Console.Write(array[i] + " ");
    if((i+1)%3==0)
        Console.WriteLine(); 
}

Long... but with comments:

List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int count = list.Count;
int numGroups = list.Count / 3 + ((list.Count % 3 == 0) ? 0 : 1); // A partially-filled group is still a group!
for (int i = 0; i < numGroups; i++)
{
     int counterBase = i * 3;
     string s = list[counterBase].ToString(); // if this a partially filled group, the first element must be here...
     if (counterBase + 1 < count) // but the second...
          s += list[counterBase + 1].ToString(", 0");
     if (counterBase + 2 < count) // and third elements may not.
          s += list[counterBase + 2].ToString(", 0");
     Console.WriteLine(s);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM