Program 5.12: Count the Wheat but Test for Overflow


class CountWheat  {

  public static void main (String args[]) {
  
    int i, j, k;

    j = 1;
    k = 0;

    for (i=1; i <= 64; i++) {
      j *= 2;
      if (j <= 0) {
        System.out.println("Error: Overflow");
        break;
      }
      k += j;
      System.out.print(k + "\t  ");
      if (i%4 == 0) System.out.println();
    } 
    System.out.println("All done!");

  }

} 
Here's the output:

% javac CountWheat.java
% java CountWheat
2            6           14              30
62           126         254             510
1022         2046        4094            8190
16382        32766       65534           131070
262142       524286      1048574         2097150
4194302      8388606     16777214        33554430
67108862     134217726   268435454       536870910
1073741822   2147483646      Error: Overflow
All done!
%

Copyright 1996 Elliotte Rusty Harold
elharo@sunsite.unc.edu
This Chapter
Examples
Home