LoopExamples

public class LoopExamples

{

    // Add up all integers from 1 through n

    public static int runningTotalWhile (int max)

    {

        int accumulator = 0; // Hold total so far

        

        while (max > 0)

        {

            accumulator += max;

            max = max - 1;

        }

        

        return accumulator;

    }

    

    public static int runningTotalDoWhile (int max)

    {

        int accumulator = 0;

        

        do

        {

            if (max > 0)

            {

                accumulator += max;

            }

            max = max - 1;

        } while (max > 0);

        

        return accumulator;

    }

    

    public static int runningTotalFor (int max)

    {

        int accumulator = 0;

        int x;

        

        for (; max > 0; max = max - 1)

        {

            accumulator += max;

        }

        

        return accumulator;

    }

    

    public static int peasantMultiply (int first, int second)

    {

        System.out.println("Multiplying " + first + " + " + second);

        

        int total = 0;

        

        if (first % 2 == 1) // first is odd

            total = first;

        

        while (first > 0)

        {

            first = first / 2;

            second = second * 2;

            

            if (first % 2 == 1)

            {

                total = total + second;

            }

            

            System.out.println(first + "\t" + second + "\t" + total);

        }

        

        return total;

    }

}

This page was last modified on 8/25/09