Users Online

· Guests Online: 35

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

#00006 Java Control Statements Part 2

 

Java Control Statements Part 2

 

 

 

1.1.            While loop in Java with examples

In the last tutorial, we discussed for loop. In this tutorial we will discuss while loop. As discussed in previous tutorial, loops are used to execute a set of statements repeatedly until a particular condition is satisfied.

Syntax of while loop

while(condition)
{
   statement(s);
}

 

How while Loop works?

In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute. When condition returns false, the control comes out of loop and jumps to the next statement after while loop.

Note: The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely.

 

Simple while loop example

class WhileLoopExample {
    public static void main(String args[]){
         int i=10;
         while(i>1){
              System.out.println(i);
              i--;
         }
    }
}

Output:

10
9
8
7
6
5
4
3
2

 

Infinite while loop

class WhileLoopExample2 {
    public static void main(String args[]){
         int i=10;
         while(i>1)
         {
             System.out.println(i);
              i++;
         }
    }
}

This loop would never end, its an infinite while loop. This is because condition is i>1 which would always be true as we are incrementing the value of i inside while loop.

Here is another example of infinite while loop:

while (true){
    statement(s);
}

 

Example: Iterating an array using while loop

Here we are iterating and displaying array elements using while loop.

class WhileLoopExample3 {
    public static void main(String args[]){
         int arr[]={2,11,45,9};
         //i starts with 0 as array index starts with 0 too
         int i=0;
         while(i<4){
              System.out.println(arr[i]);
              i++;
         }
    }
}

Output:

2
11
45
9

Example 2: Displaying Fibonacci Sequence using while loop

public class JavaExample {
 
    public static void main(String[] args) {
 
        int count = 7, num1 = 0, num2 = 1;
        System.out.print("Fibonacci Series of "+count+" numbers:");
 
        int i=1;
        while(i<=count)
        {
            System.out.print(num1+" ");
            int sumOfPrevTwo = num1 + num2;
            num1 = num2;
            num2 = sumOfPrevTwo;
            i++;
        }
    }
}

Output:

Fibonacci Series of 7 numbers:0 1 1 2 3 5 8

 

Example 3: Program to display the fibonacci series based on the user input

This program display the sequence based on the number entered by user. For example – if user enters 10 then this program displays the series of 10 numbers.

import java.util.Scanner;
public class JavaExample {
 
    public static void main(String[] args) {
 
        int count, num1 = 0, num2 = 1;
        System.out.println("How may numbers you want in the sequence:");
        Scanner scanner = new Scanner(System.in);
        count = scanner.nextInt();
        scanner.close();
        System.out.print("Fibonacci Series of "+count+" numbers:");
 
        int i=1;
        while(i<=count)
        {
            System.out.print(num1+" ");
            int sumOfPrevTwo = num1 + num2;
            num1 = num2;
            num2 = sumOfPrevTwo;
            i++;
        }
    }
}

Output:

How may numbers you want in the sequence:
6
Fibonacci Series of 6 numbers:0 1 1 2 3 5

 

Example 2: Finding Factorial using while loop

public class JavaExample {
 
    public static void main(String[] args) {
 
         //We will find the factorial of this number
        int number = 5;
        long fact = 1;
        int i = 1;
        while(i<=number)
        {
            fact = fact * i;
            i++;
        }
        System.out.println("Factorial of "+number+" is: "+fact);
    }
}

Output:

Factorial of 5 is: 120

 

Example 3: Finding factorial of a number entered by user

Program finds the factorial of input number using while loop.

import java.util.Scanner;
public class JavaExample {
 
    public static void main(String[] args) {
 
         //We will find the factorial of this number
        int number;
        System.out.println("Enter the number: ");
        Scanner scanner = new Scanner(System.in);
        number = scanner.nextInt();
        scanner.close();
        long fact = 1;
        int i = 1;
        while(i<=number)
        {
            fact = fact * i;
            i++;
        }
        System.out.println("Factorial of "+number+" is: "+fact);
    }
}

Output:

Enter the number: 
6
Factorial of 6 is: 720

 

1.2.            do-while loop in Java with example

In the last tutorial, we discussed while loop. In this tutorial we will discuss do-while loop in java. do-while loop is similar to while loop, however there is a difference between them: In while loop, condition is evaluated before the execution of loop’s body but in do-while loop condition is evaluated after the execution of loop’s body.

Syntax of do-while loop:

do
{
   statement(s);
} while(condition);

 

How do-while loop works?

First, the statements inside loop execute and then the condition gets evaluated, if the condition returns true then the control gets transferred to the “do” else it jumps to the next statement after do-while.

do-while loop example

class DoWhileLoopExample {
    public static void main(String args[]){
         int i=10;
         do{
              System.out.println(i);
              i--;
         }while(i>1);
    }
}

Output:

10
9
8
7
6
5
4
3
2

Example: Iterating array using do-while loop

Here we have an integer array and we are iterating the array and displaying each element using do-while loop.

class DoWhileLoopExample2 {
    public static void main(String args[]){
         int arr[]={2,11,45,9};
         //i starts with 0 as array index starts with 0
         int i=0;
         do{
              System.out.println(arr[i]);
              i++;
         }while(i<4);
    }
}

Output:
2
11
45
9

 

 

 

1.1.            Continue Statement in Java with example

Continue statement is mostly used inside loops. Whenever it is encountered inside a loop, control directly jumps to the beginning of the loop for next iteration, skipping the execution of statements inside loop’s body for the current iteration. This is particularly useful when you want to continue the loop but do not want the rest of the statements(after continue statement) in loop body to execute for that particular iteration.

Syntax:
continue word followed by semi colon.

continue;

Example: continue statement inside for loop

public class ContinueExample {
 
   public static void main(String args[]){
         for (int j=0; j<=6; j++)
         {
           if (j==4)
           {
               continue;
            }
 
           System.out.print(j+" ");
         }
   }
}

Output:

0 1 2 3 5 6

As you may have noticed, the value 4 is missing in the output, why? because when the value of variable j is 4, the program encountered a continue statement, which makes it to jump at the beginning of for loop for next iteration, skipping the statements for current iteration (that’s the reason println didn’t execute when the value of j was 4).

Flow Diagram of Continue Statement

 

Example: Use of continue in While loop

Same thing you can see here. We are iterating this loop from 10 to 0 for counter value and when the counter value is 7 the loop skipped the print statement and started next iteration of the while loop.

public class ContinueExample2 {
 
   public static void main(String args[]){
         int counter=10;
         while (counter >=0)
         {
           if (counter==7)
           {
                counter--;
                continue;
           }
           System.out.print(counter+" ");
           counter--;
         }
   }
}

Output:

10 9 8 6 5 4 3 2 1 0

 

Example of continue in do-While loop

public class ContinueExample3 {
 
   public static void main(String args[]){
         int j=0;
        do
         {
            if (j==7)
            {
                  j++;
                  continue;
            }
            System.out.print(j+ " ");
            j++;
       }while(j<10);
                   
   }
}

Output:

0 1 2 3 4 5 6 8 9 

 

1.2.            Break statement in Java with example

The break statement is usually used in following two scenarios:

a) Use break statement to come out of the loop instantly. Whenever a break statement is encountered inside a loop, the control directly comes out of loop and the loop gets terminated for rest of the iterations. It is used along with if statement, whenever used inside loop so that the loop gets terminated for a particular condition.

The important point to note here is that when a break statement is used inside a nested loop, then only the inner loop gets terminated.

b) It is also used in switch case control. Generally all cases in switch case are followed by a break statement so that whenever the program control jumps to a case, it doesn’t execute subsequent cases (see the example below). As soon as a break is encountered in switch-case block, the control comes out of the switch-case body.

Syntax of break statement:
“break” word followed by semi colon

break;

 

Example – Use of break in a while loop

In the example below, we have a while loop running from o to 100 but since we have a break statement that only occurs when the loop value reaches 2, the loop gets terminated and the control gets passed to the next statement in program after the loop body.

public class BreakExample1 {
   public static void main(String args[]){
      int num =0;
      while(num<=100)
      {
          System.out.println("Value of variable is: "+num);
          if (num==2)
          {
             break;
          }
          num++;
      }
      System.out.println("Out of while-loop");
  }
}

 

Output:

Value of variable is: 0
Value of variable is: 1
Value of variable is: 2
Out of while-loop

 

Example – Use of break in a for loop

The same thing you can see here. As soon as the var value hits 99, the for loop gets terminated.

public class BreakExample2 {
 
   public static void main(String args[]){
         int var;
         for (var =100; var>=10; var --)
         {
             System.out.println("var: "+var);
             if (var==99)
             {
                  break;
             }
          }
          System.out.println("Out of for-loop");
   }
}

Output:

var: 100
var: 99
Out of for-loop

 

Example – Use of break statement in switch-case

public class BreakExample3 {
 
   public static void main(String args[]){
         int num=2;
               
         switch (num)
         {
             case 1:
                System.out.println("Case 1 ");
                break;
             case 2:
                System.out.println("Case 2 ");
                break;
             case 3:
                System.out.println("Case 3 ");
                break;
             default:
                System.out.println("Default ");
         }
   }
}

 

Output:

Case 2

In this example, we have break statement after each Case block, this is because if we don’t have it then the subsequent case block would also execute. The output of the same program without break would be Case 2 Case 3 Default.

 


Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.70 seconds
10,254,943 unique visits