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

1 Answer

0 votes
#include <iostream>

int main() {
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; 
    int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array

    for (int i = 0; i < size; i += 2) {
        std::cout << "Group: ";
        std::cout << arr[i]; // Print the first element in the group
        if (i + 1 < size) { // Check if the next element exists
            std::cout << ", " << arr[i + 1]; // Print the second element in the group
        }
        std::cout << std::endl;
    }
}


/*
run:

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

*/

 



answered Jun 20, 2025 by avibootz
...