JAVATM- The Beginnings

Loops

Let’s say our program needs to increment and print a variable three times. We can write assignment and println statements, then copy and paste them twice.

        int x = 0;

        x = x +1;

        System.out.println(x);                // Prints 1

        x = x +1;

        System.out.println(x);                // Prints 2

        x = x +1;

        System.out.println(x);                // Prints 3

        System.out.println(“Done”);        // Prints Done

But what if we make a mistake while copying and pasting?

        int x = 0;

        x = x +1;

        System.out.println(x);                // Prints 1

        x = x +1;

        System.out.println(x);                // Prints 2

        System.out.println(x);                 // Oops! Prints 1

        System.out.println(“Done”);        // Prints Done

And what if we needed to perform these operations 1000 times instead of three? It would be unproductive to copy and paste these statements 999 times. Instead, we place them inside a loop.

Section 1 - while Loops

        int x  = 0;

        while (x < 3)

        {

            x = x + 1;

            System.out.println(x);        // Prints 1, 2, and 3 on separate lines

        }

        System.out.println(“Done”);        // Prints Done

Copyright ©2017 by Ralph Lecessi Incorporated. All rights reserved.



Back to ralphlecessi.com