How to print array elements in groups of 2 with C#

1 Answer

0 votes
using System;

class Program
{
    static void Main()
    {
        int[] array = { 1, 2, 3, 4, 5, 6, 7 };
        int len = array.Length;

        for (int i = 0; i < len; i += 2) {
            if (i + 1 < len) {
                Console.WriteLine($"Group: {array[i]}, {array[i + 1]}");
            }
            else {
                // Handles the last element if the array length is odd
                Console.WriteLine($"Group: {array[i]}"); 
            }
        }
    }
}



/*
run:

Group: 1, 2
Group: 3, 4
Group: 5, 6
Group: 7

*/

 



answered Jun 21, 2025 by avibootz
...