How to print array elements in groups of 2 with C

1 Answer

0 votes
#include <stdio.h>

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

    for (int i = 0; i < size; i += 2) {
        if (i + 1 < size) {
            printf("Group: %d, %d\n", arr[i], arr[i + 1]);
        } else {
            // Handle the case where the array has an odd number of elements
            printf("Group: %d\n", arr[i]);
        }
    }

    return 0;
}


   
/*
run:
   
Group: 1, 2
Group: 3, 4
Group: 5, 6
Group: 7, 8
 
*/

 



answered Jun 20, 2025 by avibootz
...