MOD example

  1. FOR a=1 TO 16
  2. IF a MOD 4 = 0 THEN PRINT_NEWLINE
  3. PRINT *
  4. NEXT

The above code will print a 4 x 4 square of stars. Line 2 contains the modulus operator. The following table shows what the a MOD 4 will produce -

A
A MOD 4
1 1
2 2
3 3
4 0
5 1
6 2
7 3

So every time A is cleanly divisable by 4 it will print a new line. This allows us to create patterns without haveing to use nested FOR loops. The above code is simpler to understands than the nested FOR loop solution but is not more efficent. In fact it would perform slower.

This is a classic example of the trade off between performance and maintainability. When coding you have to decide what is the main priority.Modern code tends to aim to be more maintainable rather than efficent. This is due to the rapid increase of computing power available.

Java version of the above code..

for (int a =1; a<=16; a++){
    if (a % 4 == 0) {
        System.out.println();
    }
    System.out.print("*");
}