Friday, October 06, 2006

While, Do... While and For statements

I am going to explain the 3 loops and how are they used. Ms Dora and Derrick, feel free to edit.

While

Format:
while (condition)
{
Execute statement
}

Usually, an integer is used to control how long we want to loop the action. In this example, I am using count, since you are familiar with it.

Supposingly, you want to print "Hello Java!" 7 times.

1)To start off, lets declare count.

int count = 0;

2)Then, we write the while statement.

while (count < 6) <-- this means that the loop will continue running until count reaches 7.
{System.out.println("Hello Java!"); <-- What we want to do
count ++} <-- Adds count by 1 per loop so that count will actually reach 7 and finish the loop.

Therefore, the statement "
System.out.println("Hello Java!");" would run 7 times. Why? Because the statement is repeated 7 times, since the statement will run when count is 0, 1, 2, 3, 4, 5 and 6 and stops when count reaches 7.

Do... While

Format:
do
{Actions - What you want to loop}
while (perimeters - How long you want it to loop)

Basically, a Do... While loop is very similiar to the While loop, just adding a 'do'. Simple?
This is how you convert the while statement I did just now.

do
{System.out.println("Hello Java!"); <-- the action
count ++ <-- counting adds one.}
while (count < 6 <--- Makes it repeat 7 times. Same logic.)

For

Format:
for ( initial value ; max value ; increment value )
{Actions}

The For statement might be the hardest of the 3, but its still easy anyways.
The initial value is the value which you want to start off with.
The max value is the value which you want to end off with.
The increment value is how much you want to increase the value by.
If the initial value is 3, the max value is 10, and the increment value is 2, the statement would run 4 times, at values 3, 5, 7 and 9.

Using the first(and only) example, the statement would look like:
for (count = 0; count > 6, count ++)
{System.out.println("Hello Java!");}

-------------------------------------------------------------------------------------------
So yes, this is my 2 cents worth. Have fun programming!

No comments: