#include <stdio.h> #include <stdlib.h> /* Puzzle C02 -- print each element in an array of ints, 10 elements per line */ void printArray( int arr[], int size ) { const int N = 10; int j; for ( j=0; j<size; j++ ) { if ( j%N == N-1 ) printf("%4d\n", arr[j] ); else printf("%4d ", arr[j] ); } } int main(int argc, char *argv[]) { int x[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 }; printArray( x, 40 ); printf("\n"); system("pause"); return 0; }
Comments:
The modulo operation j%N
is used to
convert the ascending sequence of array indexes
(0,1,2,3,4,5,6,7,8,9,10,11,12,...)
into a repeating sequence
(0,1,2,3,4,5,6,7,8,9,0,1,2,...).
Everytime the repeating sequence hits "9",
a newline character is output,
which means 10 values are output per line.
This use of the modulo operation is common.