Programming languages provide various control structures that allow for more complicated execution paths.There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages:
As we mentioned earlier, the programming you are doing now is sequential programming. This means that flow is downward, from top to bottom, with every line of code being executed, unless you tell Java otherwise.
You saw in the last section that one way to "tell" Java not to execute every line is by using IF Statement to section off areas of code.
Another way to interrupt the flow from top to bottom is by using loops. A programming loop is one that forces the programme to go back up again. If it is forced back up again you can execute lines of code repeatedly.
As an example, suppose you wanted to add up the numbers 1 to 10. You could do it quite easily in Java like this:
int addition = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;
But you wouldn't really want to use that method if you needed to add up the numbers 1 to a 1000. Instead, you can use a loop to go over a line of code repeatedly until you've reached 1000. Then you can exit the loop and continue on your way.
Java programming language provides the following types of loop to handle looping requirements. Click the following links to check their detail.
Loop Type | Description |
---|---|
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. | |
Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable. | |
do...while loop
| Like a while statement, except that it tests the condition at the end of the loop body |
In today's article we will understand how to work with loop in Java programming. We will talk about the topics below:
- For Loop in Java Programming
- While Loop in Java Programming
- Do while Loop in Java Programming
- Use of continue in Java Programming
- Use of break in Java Programming
These topics are very important to understand, when you are using the loops in your applications. Because sometimes we need to break or continue any iteration in loops. As you know we use the loops in any programming language just for the iterations.
Loop :
There are three types of looping concepts in Java Programming as we used in C++. These are used for different purpose, and we can use them to run same iteration and result will be same too. But their aim is change lets check the syntax in listing 1:
Listing 1: Syntax:
For(intial condition; final condition; increment/decrement) { //Statements here we will use the statements or conditions also } While(Condition) { //Statements here we will use the statements or conditions also } Do{ // Statements here we will use the statements or conditions also }while(condition);
For Loop :
We use for loop, when we know how much it should be repeat the iteration. It is very useful at that time when we fully agree about its limit. Because sometimes we want to repeat an iteration to given conditions, as we want to write a line just 1000 times. So the for loop is very useful for it to write it from 1 till 1000. Let’s check it in listing 2 for details how we can use it, in java Programming.
Listing 2: Use of For loop in Java Programming
public class ForLoop{ public static void main(String args[]) { //printing in ascending order //from 1 to 10 //using increment operator for(int i=1; i<=10; i++) { System.out.print(i+" "); } System.out.println(); //printing in descending order //from 10 to 1 //using decrement operator for(int i=10; i>=1; i--) { System.out.print(i+" "); } } }
In this listing 2 example there is a simple program. I gave the class name as ForLoop and in the main method I used for loop to times. In the first loop, it is increasing the iteration from 1 to 10 and in the second loop it is decreasing the iteration from 10 to 1. As I told you in the syntax we can use increment and decrement operators in for loop.
While Loop :
We use while loop in Java Programming to certain number of iterations. And it will not work like for loop. Let’s check it in listing 3 for details, but in the listing 3 we use the same program which we did in listing 2. But we will change for loop in while.
Listing 3: Use of While Loop in Java Programming
public class WhileLoop{ public static void main(String args[]) { //printing in ascending order //from 1 to 10 //using increment operator int i = 1; while(i <= 10) { System.out.print(i+" "); i++; } System.out.println(); //printing in descending order //from 10 to 1 //using decrement operator i = 10; while (i >= 1) { System.out.print(i+" "); i--; } } }
Do while Loop :
The do while loop is good to use, because it will run or execute once at any cost. It is similar like while loop. For more details about the do while loop. Let’s we check the listing 4.
Listing 4: Use of Do While Loop in Java Program
public class DoWhileLoop{ public static void main(String args[]) { //printing in ascending order //from 1 to 10 //using increment operator int i = 1; do { System.out.print(i+" "); i++; }while(i <= 10); System.out.println(); //printing in descending order //from 10 to 1 //using decrement operator i = 10; do { System.out.print(i+" "); i--; }while (i >= 1); } }
In the listings 2, 3, & 4 we use the for loop, while loop and do while loop. In these examples there are fully simple and easy examples. Which are defining the correct use of all three loops. These loops sometimes do something different, because during the programming we create complex algorithms so we become confuse. Which control statements should be use now, for example we are creating an application and we are giving options to the user to choose the options and use the application. At that time we commonly we use the while or do while loop. Because using for loop becomes so difficult that type of algorithms. Let’s check the listing 5 for details.
Listing 5: Using Control statement in Java Programming
import java.util.Scanner; public class ControlStatment{ public void Display(){ System.out.println("Welcome to Mr.bool"); } public void ForLoopSytax(){ String syntx = "for(initial;final;incre/decre){statment}"; System.out.println(syntx); } public void WhileLoopSytax(){ String syntx = "while(condition){statment}"; System.out.println(syntx); } public void DoWhileLoopSytax(){ String syntx = "do{statment}while(condition);"; System.out.println(syntx); } public void Application(){ Scanner input = new Scanner(System.in); char letter; letter = (char)input.nextInt(); do { Display(); System.out.println("Please Choose Any Option"); System.out.println("Press [F] For For Loop Syntax.."); if(letter == 'F' || letter == 'f') { ForLoopSytax(); } System.out.println("Press [D] For Do While Loop Syntax.."); if(letter == 'D' || letter == 'd') { DoWhileLoopSytax(); } System.out.println("Press [W] For While Loop Syntax.."); if(letter == 'W' || letter == 'w') { WhileLoopSytax(); } System.out.println("Press [N/n] For Exit From The Application"); } while(letter != 'N' || letter != 'n'); } public static void main(String args[]){ ControlStatment CS = new ControlStatment(); CS.Application(); } }
In the listing 5, the program will be stop when the user will input N or n letter. If the user input any other as mentioned in the program so it will call the methods according to the letter. We can use the loops for any purpose in our programs. We use the loops to control the situations or control the iterations in the programming.
Now we will use some keywords with loops iterations. These keywords are being used to make more powerful execution of the iterations in loops. These keywords are continue and break.
Keyword Continue :
The keyword continue is used in the control statements with condition statements. Control statements mean that we use continue commonly in loops when we are using the conditional statements in loops. The continue statement will continue the iteration when the conditional statement is true.
Keyword Break :
The keyword break is used to stop the iterations in control statements. Sometimes we need to stop the loops at a specific point. We also use the conditional statements in this case, when the conditional statement is true then iteration will be stop.
NOTE: We can use continue and break keywords in a single loop iterations when we are using the conditional statements. It depends on us when conditional statement is true or false what it should to do? Let’s check the listing 6 for details about the break and continue keywords.
Listing 6: Break Keywords
public class Keyword{ public static void main(String args[]){ for(int i=1; i<=10; i++) { if(i == 5) { System.out.println("Loop stopped at 5th iteration"); break; } } } }
As you can see in the listing 6, when the iteration reached at the 5 from 1. The iteration stopped due to break keyword. Now lets we use the continue keyword in listing 7
Listing 7: Continue Keyword
public class Keyword{ public static void main(String args[]){ for(int i=1; i<=10; i++) { if(i % 2 == 0) { System.out.printf("\nLoop is at %dth iteration..",i); continue; } else if(i == 5) { System.out.printf("\nLoop stoped at %dth iteration",i); break; } } } }
In this listing 7, I used both keywords continue and break. When if condition is true so the iteration will be stop at 5th iteration, otherwise the else will be true and the iteration will be continue.
List of Looping Program Example
- Pattern program 1
- Pattern program 2
- Pattern program 3
- Pattern program 4
- Pattern program 5
- Pattern program 6
- Pattern program 7
- Pattern program 8
- Pattern program 9
- Pattern program 10
- Pattern program 11
- Pattern program 12
- Pattern program 13
- Pattern Program 14
- How to find prime no.
- To check if a number is Armstrong number using java
- Java program to find factorial
- Java program for binary search
- Java program for linear search
- Write a program for print Fibonacci series
- Find average integer number using for-each loop.
- Write a Program for Signed right shift operator
- Write a Program for Unsigned right shift operator
- Write a Program for left shift operator
- Write a Program for Series
- How to find Palidrom
List of Looping Optimize Solution Program Example
Comments
Post a Comment