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++) {
      k += j;
      if (k <= 0) {
        System.out.println("Error: Overflow");
        break;
      }
      System.out.print(k + "\t  ");
      if (i%4 == 0) System.out.println();
      j *= 2;
    } 
    System.out.println("All done!");

  }

} 
Here's the output:

% java CountWheat
1	  3	  7	  15	  
31	  63	  127	  255	  
511	  1023	  2047	  4095	  
8191	  16383	  32767	  65535	  
131071	  262143	  524287	  1048575	  
2097151	  4194303	  8388607	  16777215	  
33554431	  67108863	  134217727	  268435455	  
536870911	  1073741823	  2147483647	  Error: Overflow
All done!

Copyright 1996, 2002 Elliotte Rusty Harold
elharo@metalab.unc.edu
This Chapter
Examples
Home