previous | start | next

Off By 1

Initial value of 0 or 1?

Use < or <=?

The wrong choice(s) can cause the number of repetitions of a loop body to be off by 1. Here is an example.

Problem: Select as many items as possible so that the total weight is <= a specified target weight.

Is the loop in the code below correct or is it off by 1?

import java.util.Scanner;
public class PackingApp
{
 public static void main(String[] args)
 {
  int[] wt = {1, 2, 3, 5, 9, 15, 15, 16, 20};
  int targetWeight;
  Scanner in = new Scanner(System.in);

  targetWeight = in.nextInt();                             
  int k = 0;   // Number of items packed so far            
  int sum = 0; // Total Weight of packed items             

  while( sum <= targetWeight ) 
  {
    sum += wt[k];
    k++;
  }
  System.out.printf("target weight = %d, " +
                    "packed weight = %d, " +
                    "number items packed = %d\n",
                    targetWeight, sum, k);
 }
}


previous | start | next