Java 06 : Loop

Sometime in our program we want to do same thing more than one time. The means we want to repeat same thing over and over again until you decide it’s time to stop. In programming we refer to this type of statement as repetition statement. If you want to display a message ten time, logical thing to do is write ten output statements in our program.

public class DisplayMessages{
    public static void main(String[] args){
        System.out.println("Hello world");
        System.out.println("Hello world");
        System.out.println("Hello world");
        System.out.println("Hello world");
        System.out.println("Hello world");
        System.out.println("Hello world");
        System.out.println("Hello world");
        System.out.println("Hello world");
        System.out.println("Hello world");
        System.out.println("Hello world");
    }
}

The same program can written using repetition statement like this.

public class DisplayMessages{
    public static void main(String[] args){
        for( int count = 1; count <= 10; count++){
            System.out.println("Hello world");
        }
    }
}

Both program produce the same output.

Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world

Let’s look how to write repetition statements in our program

The repetition statement syntax

for(initial_value; stopping_condition; update){
       // loop body
}

In java there are three types of repetition statement or looping statement:

  • while
  • do… while
  • for

The first syntax is belongs to for loop. The first line contains three parts, the initial value for variable, stopping condition is a Boolean expression used to determine when to stop looping. The last is updating normally increment operation used to update value of variable used in stopping condition.

for( int count = 1; count <=10; count++){
    System.out.println("Hello world");
}

What this snippet of code means. First count variable is initialized to 1 so this looping statement will start with count value being 1. After that we check for the stopping condition, even though we just started the looping statement, we must check this condition before proceeding into the loop statement body. So count<=10 means 1<=10 because current value of count is 1. This expression will evaluate to true. True means enter loop body.

Inside of the loop body is output statement, so the message will be displayed. There is no more statement after this statement so loop statement updates the value of count. Count is incremented to one so the new value count is 2, now this statement goes back to stopping condition, 2 <=10 still true so the message is displayed again, count value is updated. This process will continue on until 11<=10 which is false expression, so the loop statement will exit now.

The while loop statement executes same as for loop. The way of writing is different; the syntax will look like this.

initial_value;
while(stopping_condition){
       // statements
       // update;
}

The flow chart is similar to for looping statement. We can rewrite the same code we write using for loop using while.

int count = 1;
while(count <= 10){
    System.out.println("Hello world");
    count++;
}

So why there are two different statement to do exactly same thing. When we use this two statement are different. For loop is used when we know exactly how many times this statement will be repeated.

A While loop is used when number of repetition is unknown. Most often a sentinel value is used in a while loop. A sentinel value is used in stopping condition to end the loop. The looping statement continues to loop until value specified in sentinel value is entered. For example

while(input !=0){
       //statement in loop body
       // prompt for input
}

this statement will continue looping until value 0 is entered by the user.

The last repetition statement do…while loop statement has different execution as compare to for loop and while loop statement.

This flowchart shows that the stooping condition is after the loop body, which means the loop body is entered at least once. If we write a while loop, there exist possibilities that the loop body is never entered if the stopping condition is false.

Do while loop is more appropriate if we are using a sentinel values.

import java.util.Scanner;
public class RepeatOneMoreTime{
    public static void main(Stirng[] args){
        int inputData;
        Scanner input = new Scanner(System.in);
        do{
            System.out.println("Enter a number, 0 to exit");
            inputData = input.nextInt();
            System.out.println("You entered " + inputData);
        }while(inputData != 0);
    }
}

Output

Enter a number, 0 to exit
34
You entered 34
Enter a number, 0 to exit
78
You entered 78
Enter a number, 0 to exit
100
You entered 100
Enter a number, 0 to exit
0
You entered 0

In this program the integer variable inputData plays two important roles. First it is a placeholder for input value entered by user by keyboard. Second role is it acts as sentinel value for stopping the looping statement (inputdata != 0).

Overall this program does not do any meaningful job besides keep on entering loop body until the user enters 0. Let’s say we modify this program so that it works as if we withdraw some money from ATM machine.

import java.util.Scanner;
public class RepeatOneMoreTime{
    public static void main(String[] args){
        int inputData;
        int myBalance = 1000;
        Scanner input = new Scanner(System.in);
        do{
            System.out.println("Enter a number, 0 to exit");
            inputData = input.nextInt();
            myBalance -= inputData;
            System.out.println("Balance : " + myBalance);
        }while(inputData != 0);
    }
}

Now, myBalance -= inputData; will deduct amount entered by the user from myBalance variable and assigning new value to the myBalance variable. This will continue until we enter 0.

Nested Loop

Nested loop is a loop that appears inside of another loop

for( int count = 1; count <=10; count++){
    for(int j = 1; j <= count; j++)
       System.out.print(j);
    }
    System.out.println();
}

Output

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
1 2 3 4 5 6 
1 2 3 4 5 6 7 
1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 8 9 
1 2 3 4 5 6 7 8 9 10 

A post by Cuber

Comments

Popular posts from this blog

Drawing Simple Pie Chart

VB.net connecting to SQL Server

VB.net