Learn about Looping Constructs in Java. Show
Looping is a feature that facilitates the execution of a set of functions or instructions repeatedly until a certain condition is fulfilled. Java provides three types of loops namely the for loop, the while loop, and the do-while loop. Loops are also known as Iterating statements or Looping constructs in Java. Imagine you are asked to print the value of 212^121, 222^222, 232^323, 242^424 …….2102^{10}210. One way could be taking a variable x=2x=2x=2 and printing and multiplying it with 2 each time. public class Main {
public static void main(String[] args) {
int x = 2;
/* printing value and multiplying it by 2 every time */
System.out.print(x + " ");
x *= 2;
System.out.print(x + " ");
x *= 2;
System.out.print(x + " ");
x *= 2;
System.out.print(x + " ");
x *= 2;
System.out.print(x + " ");
x *= 2;
System.out.print(x + " ");
x *= 2;
System.out.print(x + " ");
x *= 2;
System.out.print(x + " ");
x *= 2;
System.out.print(x + " ");
x *= 2;
System.out.print(x + " ");
}
}
Output: 2 4 8 16 32 64 128 256 512 1024
Another way is using loops. Using Looping statements the above code of 10 lines can be reduced to 3 lines. public class Main {
public static void main(String[] args) {
int x = 2;
for (int i = 0; i < 10; i++) {
System.out.print(x + " ");
x *= 2;
}
}
}
Output: 2 4 8 16 32 64 128 256 512 1024
Looping Constructs in Java are statements that allow a set of instructions to be performed repeatedly as long as a specified condition remains true. Java has three types of loops i.e. the for loop, the while loop, and the do-while loop. for and while loops are entry-controlled loops whereas do-while loop is an exit-controlled loop. A very obvious example of loops can be daily routine of programmers i.e. Eat -> Sleep -> Code -> Repeat
A computer is most suitable for performing repetitive tasks and can tirelessly do tasks tens of thousands of times. We need Loops because
To understand all these steps let us relate this to our day-to-day lives. We wake up every morning, and think of the tasks that we are going to accomplish in a day. This is just like initializing. We test several possibilities, like availability of resources, pre-planned events, etc., to check whether we can complete the tasks. For example, to attend online classes we check for a good internet connection. This can be related to test expressions. Then we complete the tasks, (eat-sleep-code) as in the body of the loop. And next day we repeat the same process. As Sunday arrives we take a break from the routine, just like that when certain test condition fails, we come out of the loop. Note Update expression doesn’t need to be increment or decrement only. It can be any update to the variable x. For example, i+=2, i*=3, or i/=5 etc. There are three types of Loops. They are explained below. The for LoopWhen we know the exact number of times the loop is going to run, we use for loop. It provides a concise way of writing initialization, condition, and increment/decrement statements in one line. Thus, it is easy to debug and also has no risk of forgetting any part of the loop, since the condition is checked before. For loop is an entry-controlled loop as we check the condition first and then evaluate the body of the loop. Syntax: for(Initialization ; Test Expression ; Updation){ // Body of the Loop (Statement(s)) } Example public class Main { public static void main(String[] args) { int maxNum = 5; /* loop will run 5 times until test condition becomes false */ for (int i = 1; i <= maxNum; i++) { System.out.println(i); } } } Output: Here, initially i is 1 which is less than maxNum so it is printed. Then i is incremented and printed until it is greater than maxNum. Example Explanation:
Working of a For LoopFirstly Initialization expression is executed. Then the test expression is evaluated. If it is true then control goes inside body of the loop or loop is terminated. After execution update expression is carried out. If the test expression evaluates to false the loop is terminated else the body of the loop again executed. This process continues until the test expression becomes false. For Loop Variations
Note: Here, for initialization and update expressions we used comma but for condition we used ‘&&’ (and) operator. Other Logical operators can also be used. public static void main(String[] args) { int totalRows = 5, totalCols = 5; int[][] matrix = new int[n][n]; // declaring a 2D array /* for loop to fill diagonal values */ for (int row = 0, col = 0; row < totalRows && col < totalCols; row++, col++) { matrix[row][col] = 1; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } //printing matrix } Output 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 In the above example, row and col two variables are initialized. And both of them are updated in update expression to get the desired index for the matrix. 2. Optional Expressions In loops, initialization expression(s), test expression(s), and update expression(s) are optional. Any or all of these are skippable. Examples: for(;;){} //Empty loop for(int i=0;;i++){} //Infinite loop for(;i<n;i++){} //initialization is done outside the loop Let's see an example where initialization is done outside the loop, condition checking and update expression are performed inside the loop. public static void main(String[] args) { int i = 0, n = 5; //initailization for (;;) { if (i > n) //condition checking and termination break; //break will terminate the loop i++; //incrementation } } Thus, all these elements of the loop are optional. Note: The loop-control expressions in a for loop statements are optional, but semi-colons must be written.
Elements of the for loop are optional but while skipping them, special care must be taken. Many times due to logical mistakes we run into an infinite loop that is not desired. For instance, for(int i = 0; i >= 0; i++){ //statements } Here, i is supposed to be greater than or equal to zero and it is incremented by one each time. The condition is going to be true for all the values of i and thus the loop will run infinitely. Another Example could be where there is not condition provided. for (int i = 0;; i++) { System.out.println("Hello World"); } Infinite loops are useful in operating systems, servers, etc. They keep on executing until shut down manually.
For Example: Enhanced for loop in Java
Syntax: for(declaration : Test Expression){ // Statements } Example: public static void main(String[] args) { int[] nums = {3, 4, 5, -1, 0, 10}; int sum = 0; // iterating through each element of the array for (int element: nums) { sum += element; } System.out.println("Sum = " + sum); } In the given program for-each loop takes each element one-by-one from the nums array and adds it to the sum. The while LoopThe while loop is used when the number of iterations is not known but the terminating condition is known. Loop is executed until the given condition evaluates to true. While loop is also an entry-controlled loop as the condition is checked before entering the loop. The test condition is checked first and then the control goes inside the loop. Although for loop is easy to use and implement, there may be situations where the programmer is unaware of the number of iterations, it may depend on the user or the system. Thus, when the only iterating and/or terminating condition is known, while loop is to be used. While loop is much like repeating if statement. Syntax: Initialization; while(Test Expression){ // Body of the Loop (Statement(s)) Updation; } Example Let us look at an example where we find the factorial of a number. So, until i is not equal to 0 while loop will be executed and i will be multiplied to variable fact. public static void main(String args[]) { int factorial = 1, number = 5, tempNum = 0; tempNum = number; // Initialization; while (tempNum != 0) { // Test Expression factorial = factorial * tempNum; --tempNum; //Updation; } System.out.println("The factorial of " + number + " is: " + factorial); } The factorial of 5 is: 120 To find the factorial of a number n n = n*(n-1)*(n-2).....*1. Here, until the number is not zero, the factorial variable is multiplied with the number and decremented. Explaination
Working of a while loopFirstly, test expression is checked. If it evaluates to true, the statement is executed and again condition is checked. If it evaluates to false the loop is terminated. The while loop Variations
public static void main(String[] args) { int j = 10; while (j >= 0) { System.out.println(j); } } In the above example, the value of j is not decremented and thus the loop is executed infinite times. Also sometimes while loop is made to run infinite times as per the requirement of the program by giving the condition to be true as shown in the example. while (true) { System.out.println("Hello World"); } ::: do-while is like the while loop except that the condition is checked after evaluation of the body of the loop. Thus, the do-while loop is an example of an exit-controlled loop. The loop is executed once, and then the condition is checked for further iterations. This loop runs at least once irrespective of the test condition, and at most as many times the test condition evaluates to true. It is the only loop that has a semicolon(;). Need for Do-While Loopfor and while loops are not evaluated if the condition is false. In some cases, it is wanted that the loop-body executes at least once irrespective of the initial state of test-expression. This is where the do-while loop is used. Syntax: Initialization; do { Body of the loop (Statement(s)) Updation; } while(Test Expression); Example: import java.util.Scanner; import javax.swing.*; public class Main extends javax.swing.JFrame { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter initial number"); int result = sc.nextInt(); // Initialization by taking input do { System.out.println("Enter number"); int temp = sc.nextInt(); System.out.println("Enter your choice \n1 Add\n2 Subtract\n3 Multiply\n4 Divide"); switch (sc.nextInt()) { case 1: result += temp; break; case 2: result -= temp; break; case 3: result *= temp; break; case 4: result /= temp; break; } System.out.println("Result is " + result + "."); System.out.println("To continue enter 1, to exit enter 0"); } while (1 == sc.nextInt()); // test Expression } } Output: Enter initial number 45 Enter number 5 Enter your choice 1 Add 2 Subtract 3 Multiply 4 Divide 4 Result is 9. To continue enter 1, to exit enter 0 1 Enter number 1 Enter your choice 1 Add 2 Subtract 3 Multiply 4 Divide 1 Result is 10. To continue enter 1, to exit enter 0 1 Enter number 8 Enter your choice 1 Add 2 Subtract 3 Multiply 4 Divide 3 Result is 80. To continue enter 1, to exit enter 0 0 The above program takes 2 numbers from the user and performs operations on it. The program runs at least once and at max as many times, the user wants to continue. It first takes a number initially. It then asks for another number and operation to be performed with them. It prints the result and asks the user if they want to continue. If they enter 1, it takes the previous result and a new number and again performs the operation as required by the user, and this continues till the user wants to continue. Working of a do-while loopThe statement is executed once no matter what the initial condition is. Then the condition is checked. If it is true then the loop is executed else it is terminated. Condition is checked at the end of the execution of the body. Since the loop is a function it is possible to declare variables inside the loop. The variables declared inside the loop are called local variables and their scope is only inside the loop. They cannot be accessed outside the loop. They are created and discarded each time the loop is executed. For instance for(int i=2;i>=0;i--){ int x = i+2; //local variable System.out.println("local variable x : "+x); } Output: local variable x : 4 local variable x : 3 local variable x : 2 BUILD SUCCESSFUL (total time: 0 seconds) A nested loop is a loop statement inside another loop statement. In a nested loop, for each iteration of the outer loop, the entire inner loop is executed. For instance, if the outer loop is to be run m times and the inner loop is to be run n times, the total time complexity of the nested loop is m*n i.e. for all m iterations of the outer loop, the inner loop is run n times. Loops can be nested with the same type of loop or another type of loop there is no restriction on the order or type of loop. For example for loop can be inside a while and vice versa, or a do-while loop can be under the do-while loop. while (condition) { for (initialization; condition; increment) { do { //statement of do-while loop } while (condition); //statement of for loop } //statement of while loop } Nested Loops are used to print multidimensional arrays, patterns, etc. Let us see an example of printing Pascals's Triangle using nested loops public class main { public static int factorial(int num) { if (num == 0) return 1; return num * factorial(num - 1); } public static void main(String[] args) { int totalRows = 4, rows = 0, spaces = 0, number = 0; for (rows = 0; rows <= totalRows; rows++) { for (spaces = 0; spaces <= totalRows - rows; spaces++) { // for left spacing System.out.print(" "); } for (number = 0; number <= rows; number++) { // nCr formula System.out.print(" " + factorial(rows) / (factorial(rows - number) * factorial(number))); } System.out.println(); // for newline } } } Output: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 This function uses nested loops. The outer for loop keeps the record of rows. Two inner loops are responsible for printing spaces and the value of ^n^Cr of the rows and the number. The first for loop prints space from 0 to totalRows - rows. And the second for loop prints the value of ^n^Cr of the current row and current number. The number is incremented each time the inner loop iterates but the value of rows remains the same. rows changes when both the loop iterates and terminates. Now the rows is incremented and again both the inner loops are again executed.
|