Discussion of Activity 2.6 - Experimenting with for loops

Here are our sample solutions.

Method 1: countDownFrom

public void countDownFrom(int startingValue)
{
   System.out.println("First task: counting down from " + startingValue + ".");
   for (int i = startingValue; i >= 0; i--)
   {
      System.out.println(i);
   }
}

Method 2: totalFromOneTo

public void totalFromOneTo(int finalValue)
{
   int total = 0;

   System.out.println
         ("Second task: finding the total of the numbers from 1 to " + finalValue + ".");
   for (int i = 1; i <= finalValue; i++)
   {
      total = total + i;
   }
   System.out.println("The result is " + total + ".");
}

Method 3: howManySquaresUpTo

public void howManySquaresUpTo(int limit)
{
   int count = 0;

   System.out.println
         ("Third task: finding the number of squares up to " + limit + ".");
   for(int i = 1; i*i <= limit; i++)
   {
      count++;
   }

   System.out.println
         ("There are " + count + " numbers whose squares are no bigger than " + limit + ".");
}

In this case, it is not clear how many iterations are going to take place because of the relatively complex stopping condition i*i <= limit. This may mean that a while loop is more readable.