Published July 03, 2024

Iterative Or Loop Statements In Java

A loop is a programming construct for repeatedly executing code based on a condition. Loops are categorized by when the condition is checked relative to the loop body's execution.

image

Loop is a programming construct that allows you to execute a block of code repeatedly based on a condition. Loops can be categorized based on when the loop condition is checked relative to the execution of the loop body.

These categories are commonly referred to as entry-controlled loops and exit-controlled loops.

These categories are entry-controlled and exit-controlled loops

Entry-Controlled Loop (Pre-Test Loop):

In entry-controlled loops, the loop condition is checked before the execution of the loop body. If the condition evaluates to false initially, the loop body will not be executed at all. Example of Entry-Controlled Loops:

 

while loop:

The while loop is used when you want to execute a block of code as long as a condition is true. Given condition is tested before executing the loop body.

Syntax:

while (condition) {

    // code to be executed

}

condition: It is the expression evaluated before each iteration. If it evaluates to true, the loop continues; otherwise, it terminates.

// Entry-controlled while loop

int i = 0;

while (i < 5) {

    System.out.println("Count is: " + i);

    i++;

}

for loop:

The for loop is used when you know exactly how many times you want to execute a block of code.

 

Syntax:

for (initialization; condition; update) {

    // code to be executed

}

Initialization: It initializes the loop control variable.

Condition: Expression evaluated before each iteration. If it evaluates to true then the loop continues otherwise it terminates.

Update: It updates the loop control variable after each iteration.

 

// Entry-controlled for loop

for (int i = 0; i < 5; i++) {

    System.out.println("Count is: " + i);

}

 

Exit-Controlled Loop (Post-Test Loop):

 

In exit-controlled loops, the loop condition is checked after the execution of the loop body. This means that the loop body is executed at least once before the condition is evaluated.

 

 

do-while loop

The do-while loop is similar to the while loop, but the condition is evaluated after executing the loop body. Therefore, the loop body is executed at least once.

 

 

Syntax:

do {

    // code to be executed

} while (condition);

 

// Exit-controlled do-while loop

int i = 0;

do {

    System.out.println("Count is: " + i);

    i++;

} while (i < 5);

 

Use Case 1:

Generating table of N.

Input: N=9

Output:

9 X 1 : 9

9 X 2 : 18

9 X 3 : 27

9 X 4 : 36

9 X 5 : 45

9 X 6 : 54

9 X 7 : 63

9 X 8 : 72

9 X 9 : 81

9 X 10 : 90

 

Use Case 2:

countdown from a specified number to 0

// Test Case: Countdown from 5 to 0

// Expected result: 5 4 3 2 1

 

int num=5

for (int i = num; i >= 0; i--) {

    System.out.print(i + " ");

}

 

Use Case 3:

Generating a sequence of numbers

// Expected result: 1 2 3 4 5

for (int i = 1; i <= 5; i++) {

    System.out.print(i + " ");

}

 

Use Case 4:

Performing Input Validation

// Test Case: Repeatedly prompt user until valid input positive value received.

Scanner scanner = new Scanner(System.in);

int number;

do {

    System.out.print("Enter a positive number: ");

    number = scanner.nextInt();

} while (number <= 0);

// Expected result: Valid positive number entered

 

 

 

Use Case 5:

Right angle triangle pattern coding question based on loops.

Question 1: Print a Right Angle Triangle Pattern:

Input: row :5

Output:

*

* *

* * *

* * * *

* * * * *

 

Code Solution:

public class RightAngleTrianglePattern {

    public static void main(String[] args) {

        int rows = 5;

        for (int i = 1; i <= rows; i++) {

            for (int j = 1; j <= i; j++) {

                System.out.print("* ");

            }

            System.out.println();

        }

    }

}

 

Use Case 6:

Print an Inverted Right Angle Triangle Pattern:

Input: row :5

Output:

* * * * *

* * * *

* * *

* *

*

 

Code Solution:

public class InvertedRightAngleTrianglePattern {

    public static void main(String[] args) {

        int rows = 5;

        for (int i = rows; i >= 1; i--) {

            for (int j = 1; j <= i; j++) {

                System.out.print("* ");

            }

            System.out.println();

        }

    }

}

 

Use Case 7:

Print an Equilateral Triangle Pattern:

Input: row :5

Output:

    *

   ***

  *****

 *******

*********

 

Code Solution:

public class EquilateralTrianglePattern {

    public static void main(String[] args) {

        int rows = 5;

        for (int i = 1; i <= rows; i++) {

            for (int j = 1; j <= rows - i; j++) {

                System.out.print(" ");

            }

            for (int k = 1; k <= i * 2 - 1; k++) {

                System.out.print("*");

            }

            System.out.println();

        }

    }

}

 

Use Case 8:

Print a Hollow Pyramid Pattern:

Input: row :5

Output:

          *

      *    *

    *        *

 *             *

*********

Code Solution:

public class HollowPyramidPattern {

    public static void main(String[] args) {

        int rows = 5;

        for (int i = 1; i <= rows; i++) {

            for (int j = 1; j <= rows - i; j++) {

                System.out.print(" ");

            }

            for (int k = 1; k <= i * 2 - 1; k++) {

                if (k == 1 || k == i * 2 - 1 || i == rows) {

                    System.out.print("*");

                } else {

                    System.out.print(" ");

                }

            }

            System.out.println();

        }

    }

}

 

Use Case 9:

Do..while practice questions:

Question 1: To calculate the factorial of a given number using a do...while

import java.util.Scanner;

public class FactorialUsingDoWhile {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");

        int number = scanner.nextInt();

        int factorial = 1;

        int i = 1;

        do {

            factorial *= i;

            i++;

        } while (i <= number);

        System.out.println("Factorial of " + number + " is: " + factorial);

    }

}

 

Use Case 10:

To print numbers from 1 to N (inclusive) using a do...while loop.

import java.util.Scanner;

public class PrintNumbersUsingDoWhile {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");

        int number = scanner.nextInt();

        int i = 1;

        System.out.println("Numbers from 1 to " + number + ":");

        do {

            System.out.println(i);

            i++;

        } while (i <= number);

    }

}

 

Use Case 11:

To reverse a given number using a do...while loop.

import java.util.Scanner;

public class ReverseNumberUsingDoWhile {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");

        int number = scanner.nextInt();

        int reversedNumber = 0;

        do {

            int digit = number % 10;

            reversedNumber = reversedNumber * 10 + digit;

            number /= 10;

        } while (number != 0);

        System.out.println("Reversed number: " + reversedNumber);

    }

}

 

Use Case 12:

To calculate the sum of digits of a given number using a do...while loop.

import java.util.Scanner;

 

public class SumOfDigitsUsingDoWhile {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");

        int number = scanner.nextInt();

        int sum = 0;

        int temp = number;

        do {

            sum += temp % 10;

            temp /= 10;

        } while (temp != 0);

        System.out.println("Sum of digits of " + number + " is: " + sum);

    }

}

 

 

Use Case 13:

To check whether a given number is prime or not using a do...while loop.

import java.util.Scanner;

public class PrimeNumberCheckUsingDoWhile {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");

        int number = scanner.nextInt();

        boolean isPrime = true;

        int i = 2;

        do {

            if (number % i == 0) {

                isPrime = false;

                break;

            }

            i++;

        } while (i <= number / 2);

        if (isPrime) {

            System.out.println(number + " is a prime number.");

        } else {

            System.out.println(number + " is not a prime number.");

        }

    }

}

 

Download Lecture Pdf..

Reviews

Leave a Comment