Loops in the programming language JAVA
Loops are a key element in programming that allow certain blocks of code to be executed repeatedly, as long as a certain condition is met. In Java, loops are a basic control structure that allows programmers to automate repetitive tasks, iterate through data, or manage complex algorithms. By using loops, programs become more efficient and easier to maintain. In this article, we'll explore the different types of loops in Java, how they work, and when to use them for best results.
You can read this lesson in C / C ++ on the following page: Loops in C/C++
To practice examples from this topic, go to the webpage: Loops in JAVA-examples.
Let's look at the next problem. We want to print a number of natural numbers. Now, in this case, there are a number of the first 10 natural numbers. The order to print number 1 is:
System.out.print ("1");
If we want to print other numbers, we could do this by repeating the previous command 10 times (we use Copy - Paste) and only change the value of the number that is displayed
System.out.print ("1,");
System.out.print ("2,");
System.out.print ("3,");
System.out.print ("4,");
System.out.print ("5,");
...
System.out.print ("2,");
System.out.print ("3,");
System.out.print ("4,");
System.out.print ("5,");
...
This could still be done in this way for a few numbers, but what if it is necessary to print a series of 100, 1000 numbers. Of course, this would not work in this way.
The idea of using a cycle is to write repeating commands only once, and using the command to create a cycle, for example, command for, these commands repeatedly executed, i.e. as many times as necessary.
In this example, a repeating command is
The idea of using a cycle is to write repeating commands only once, and using the command to create a cycle, for example, command for, these commands repeatedly executed, i.e. as many times as necessary.
In this example, a repeating command is
System.out.print (..
So, we will write it only once and insert within the command for which represents the cycle:
In general, the command for is written:
So, we will write it only once and insert within the command for which represents the cycle:
In general, the command for is written:
for (initialization; condition_trap; expression_of_the_loop)
{
array_of_commands;
}
{
array_of_commands;
}
In our case, there is only one order and it is written inside the curly braces and it would look like:
for (initialization; condition_trap; expression_of_the_loop)
{
System.out.print (..
}
{
System.out.print (..
}
The conditions to be written, which determine the number of repeated cycles, are written in small brackets, which are: initialization, query condition, expression_of_the_loop, and they are separated by a point-comma within this small bracket.
Initialization means that we introduce (define) a control variable, for example, which means that we reserve for its memory and give it the initial value (initializing). In this example:
Initialization means that we introduce (define) a control variable, for example, which means that we reserve for its memory and give it the initial value (initializing). In this example:
int i = 1;
The loop condition is a logical expression that can be either true or false.
i <= 10;
The cycle will be repeated as long as this condition is "true". When during a cycle they are variable and do not change, and we can change it through the loop, the condition would always be "true", i.e. the cycle would never be interrupted (the infinite cycle). In order to break it must be made that the condition is not satisfied (false). The control variable can be changed using:
expression_of_the_loop and this is usually expression like:
expression_of_the_loop and this is usually expression like:
i = i + step,
where the step is an integer that represents the value of how much it is variable and increases or decreases (if the negativ value is a value). In our example, the value i should be increased in each cycle by 1, so the loop expression will read:
i = i + 1,
This means that in the memory space and the new value is 1 higher than the previous one. For the cycle now looks like:
for (int i = 1; i <= 10; i = i+1)
{
System.out.print (..
}
{
System.out.print (..
}
The command will now be repeated 10 times, as long as <= 10. It remains to be seen what to put in the brackets of the print command. If you wrote "1", then "1,1,1,1,1,1" would be printed ...
It is necessary to put a variable that will have a value of 1 in the first cycle, in the second 2, etc. It can be exactly variable and that serves to control the number of cycles. Now we can finally write:
It is necessary to put a variable that will have a value of 1 in the first cycle, in the second 2, etc. It can be exactly variable and that serves to control the number of cycles. Now we can finally write:
for (int i = 1; i <= 10; i = i+1)
{
System.out.print( i+”, ”);
}
{
System.out.print( i+”, ”);
}
Of course, this task could be resolved with a command:
System.out.print ("1,2,3,4,5,6,7,8,9,10");
but we just wanted to showcase the order for cycles and when and why they are used.
The cycle for is normally used when we know in advance how many cycles will be, and if we do not know, then either the while or do-while cycle will be used, which will be discussed later.
For expression_frames, operator "++" can be used to increase the value of a variable and for a value of 1 instead of "i = i + 1"
The cycle for is normally used when we know in advance how many cycles will be, and if we do not know, then either the while or do-while cycle will be used, which will be discussed later.
For expression_frames, operator "++" can be used to increase the value of a variable and for a value of 1 instead of "i = i + 1"
for(int i = 1; i<=10; i++)
{
System.out.print( i+”, ”);
}
{
System.out.print( i+”, ”);
}
Example: Sum of natural numbers:
Text of the task: Summarize the first 10 natural numbers using the cycle.
And this task could be solved by the order
System.out.print ("" + (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10));
but we want to show how to use the cycle for a given sum (it is convenient when there are many numbers). The idea is to add in each cycle a natural number in a variable that represents a sum. These natural numbers would be marked with a variable in the cycle as in the previous case (it is convenient because this variable changes from 1 to 10 during the cycle with step 1, so that it through cycles actually represents those natural numbers to be added.
First, you need to introduce a variable that will represent a sum:
int sum = 0;
Then one should be added to the collection. Written without a cycle, it would look like:
sum = sum + 1;
sum = sum + 2;
sum = sum + 3;
sum = sum + 4;
...
sum = sum + i;
...
sum = sum + 10;
sum = sum + 2;
sum = sum + 3;
sum = sum + 4;
...
sum = sum + i;
...
sum = sum + 10;
but instead we use a cycle:
for(int i = 1; i <= 10; i++)
{
sum= sum+ i;
}
{
sum= sum+ i;
}
The final sum will be formed only after the end of the cycle. A complete example is shown in the code below.
class SumOfNumbers
{
public static void main(String[]args)
{
}{
int sum=0;
for(int i = 1; i<=10; i= i+1)
{
System.out.println("sum = "+ sum);
}for(int i = 1; i<=10; i= i+1)
{
sum = sum + i;
}System.out.println("sum = "+ sum);
Example: Average grade
Text of the text: Load the object number n, then load the grades from the n objects, compile them and calculate the average grade. Display the result on the screen.
Instructions: Load n through the Input dialog. Since there are more ratings for the load to use for the cycle. The compilation of the grades is done in a cycle as done in the previous example. The time when the final sum of the estimates is calculated, and this is after the cycle, can be further calculated by the average.
Instructions: Load n through the Input dialog. Since there are more ratings for the load to use for the cycle. The compilation of the grades is done in a cycle as done in the previous example. The time when the final sum of the estimates is calculated, and this is after the cycle, can be further calculated by the average.
While loop in java with a condition at the beginning
In general, the cycle looks like:
Unlike the for that used when we know the number of cycles in advance, while it is used when we do not know in advance when the cycle will be interrupted. Let's look at the following example:
Example Quiz:
Text of the Task: Load the points awarded for the current question in a quiz. Arrange after how many questions a candidate will reach a value of 30 points, if for each question he can win 1-10 points. Counting points will be terminated after a maximum of 10 questions.
We will add a variable that will represent the current value of the number of points in question, as well as the variable that represents the total number of points won which have a starting value of 0 before the first question;
We will add a variable that will represent the current value of the number of points in question, as well as the variable that represents the total number of points won which have a starting value of 0 before the first question;
int score;
int totalScore=0;
Scanner scanner=new Scanner(System.in);
int totalScore=0;
Scanner scanner=new Scanner(System.in);
Points will be loaded through the cycle and added to the total number of points:
while(totalScore < 30 )
{
{
System.out.println("Enter the number of points");
score=scanner.nextInt();
totalScore= totalScore+ score;
}score=scanner.nextInt();
totalScore= totalScore+ score;
When the total value of the points reaches a value of 30 cycles will be interrupted. In order to count cycles we introduce an integer variable whose initial value is zero, and when each cycle is realized, this number is increased by 1;
int score;
int totalScore = 0;
int numberCycle = 0;
Scanner scanner=new Scanner(System.in);
while (totalScore <30)
{
int totalScore = 0;
int numberCycle = 0;
Scanner scanner=new Scanner(System.in);
while (totalScore <30)
{
System.out.println("Enter the number of points");
score= scanner.nextInt();
totalScore = totalScore + score;
numberCycle ++; // Increases the number of cycles by 1
}score= scanner.nextInt();
totalScore = totalScore + score;
numberCycle ++; // Increases the number of cycles by 1
In the end, we will ensure that the number of cycles is max. 10. This can be done by the existing condition
totalScore <30
expand with additional condition
totalScore <30 && numberCycle <10.
The whole code is now given in the picture below:
totalScore <30
expand with additional condition
totalScore <30 && numberCycle <10.
The whole code is now given in the picture below:
While loop in java with the condition in the end
CYCLE while with the condition in the end this type of cycle is similar to the while cycle, with the difference that the condition is set at the end of the cycle, not at the beginning:
This practically means that in the do-while loop, a series of commands must be done at least once, while while the cycle does not have to go one time.
Let's look at the following example:
Let's look at the following example:
Example: Temperature:
Text of the task: Load the temperature values that are read every hour at a certain measurement location. The reading is canceled when the -100 value is loaded. Determine the number of loaded temperatures.
In this case, it is not known how many cycles will be needed (the number of temperature readings), in fact, the value that should be determined in this case. Cycles will in any case last as long as the condition is satisfied that the load value is different from -100 (the assumption is that such a temperature is not possible, so this value is used to terminate the cycle).
In the first part of the task, we define the variable temperature:
Scanner scanner=new Scanner(System.in);
double temperature;
double temperature;
Within the cycle, since we use the do-time loop, at least one temperature reading will be performed. Further reading will depend on whether the loaded value is different from -100. The cycle would look like this:
do
{
while(temperature != -100);
{
temperature=scanner.nextDouble()
}while(temperature != -100);
If the first value is -100, only the first value of the temperature will be loaded, and the cycle does not continue. A complete example now looks like:
The number of loaded temperatures is equal to the number of cycles. To determine the number of cycles we use the integer variable number of the cycle as in the previous example.
Tasks that are more convenient to use for the cycle because we know the number of cycles in advance can be resolved, however, by using the while or do-while loop. An example of calculating a collection of the sequence of the first 10 natural numbers using the while cycle would look:
Since the loop within the small bracket is only the condition of the queue, the initialization, which in the for the cycle was also inside a small bracket, is written here in front of the cycle, while the expression_page in which the step of increasing the control variable is written, is written as one of the commands within the cycle.
The number of loaded temperatures is equal to the number of cycles. To determine the number of cycles we use the integer variable number of the cycle as in the previous example.
Tasks that are more convenient to use for the cycle because we know the number of cycles in advance can be resolved, however, by using the while or do-while loop. An example of calculating a collection of the sequence of the first 10 natural numbers using the while cycle would look:
Since the loop within the small bracket is only the condition of the queue, the initialization, which in the for the cycle was also inside a small bracket, is written here in front of the cycle, while the expression_page in which the step of increasing the control variable is written, is written as one of the commands within the cycle.
Nested loops(Cycle within the cycle)
A cycle can also be found within another cycle as one of the orders of an external cycle:
for (initialization_1; loop_condition_1; loop_expression_1)
{
for (initialization_2; loop_condition_2; loop_expression_2)
{
commands_array;
}
}
{
for (initialization_2; loop_condition_2; loop_expression_2)
{
commands_array;
}
}
Example: Matrix
This can be explained in the following example:
Text of the task: Print a matrix consisting of 10 rows and 10 columns to look like in the picture:
.
To print one line of numbers we use for a cycle:
.
To print one line of numbers we use for a cycle:
for( int j = 0; j < 10; j++)
{
System.out.print((j+1)+" ");
}
{
System.out.print((j+1)+" ");
}
Here the value ( j + 1) is used to print the first row because the initial value of j is not 1 already 0.
Since nine more lines of this kind have to be printed, it is necessary to repeat for the command another 9 times. We will add another for the cycle (external) so that this previous for the cycle is the command of nesting within the external for the cycle.
Since nine more lines of this kind have to be printed, it is necessary to repeat for the command another 9 times. We will add another for the cycle (external) so that this previous for the cycle is the command of nesting within the external for the cycle.
for( int i = 0; i < 10; i++)
{
for( int j = 0; j < 10; j++)
{
System.out.print((j+1)+" ");
}
System.out.println(); //New row
}
{
for( int j = 0; j < 10; j++)
{
System.out.print((j+1)+" ");
}
System.out.println(); //New row
}
The control variable is now the current line, and the control variable j belonging to the inner loop represents the index of the current column. This code needs to be changed slightly because
System.out.print ((j + 1) + " ");
it always prints the numbers 1-10, and for i = 3, for example (4th order), it should print values for (i * 10) larger in this case by 30 higher (31-40). This means that the command needs to be changed:
System.out.print (10 * and + (j + 1) + " ");
System.out.print ((j + 1) + " ");
it always prints the numbers 1-10, and for i = 3, for example (4th order), it should print values for (i * 10) larger in this case by 30 higher (31-40). This means that the command needs to be changed:
System.out.print (10 * and + (j + 1) + " ");
for-each loops in java
for each loops were introduced with the JAVA 5 version and are used when data arrays are used and it is necessary to go through the elements of that array iteratively through cycles. For example, if we were to define the following array:
String [ ] planets={"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptum","Pluto"};
In order to print a previously defined array of Strings, which represents the set of planets in the solar system, it is convenient to use a for-each loop. Here the command is also written as for, but without the control expressions, with the variable "i". The following syntax is used instead:
for(String planet:planets)
{
{
System.out.println(planet);
}The "planet" reference here is a variable of the same type as the elements of the "planet" array. In each subsequent cycle, the value of the planet variable will be the element that is in the next position of the array. So, after executing the previous command, the following will be written on the standard output:
Mercury
Venus
Earth
...
Venus
Earth
...
This same example could also be done with a simple for loop:
for(int i = 0; i < planets.length;i++)
{
{
System.out.println(planets[i]);
}This example is easier to do with a for-each loop, but there are some examples that can't be done that way, and a regular for loop must be used instead. For example. if we want to print a sequence of integers backwards:
for(int i = 10; i > 0;i--)
{
{
System.out.println(i);
}This would output the following:
10
9
8
...
9
8
...
for each loops with collections and arrays of objects in Java
The for each loop is suitable for looping through a collection or array of java objects. Suppose that the following collection of objects (ArrayList) is defined in Java:
ArrayList < Employee> allEmployees = new ArrayList < >();
The list represents a collection of objects of the Employee class. If we create 3 such objects and insert iḫ into the list, then we would use a for-eacḫ loop to print the data, as in the following figure:
The Employee class would be:
In newer versions of Java, a foreach loop can be written as follows:
FAQ: Common Issues and Choosing the Right Loop in Java
What are common mistakes when using loops in Java?
- Infinite Loops: One of the most common mistakes is accidentally creating an infinite loop. This happens when the loop's terminating condition is never met, causing the loop to run indefinitely. For example, in a while loop, if you forget to update the loop variable or if the condition is always true, the loop will never exit.
int i = 0;
while (i < 10) {
while (i < 10) {
System.out.println(i);
// Missing i++ here leads to an infinite loop
}// Missing i++ here leads to an infinite loop
Off-by-One Errors: These errors often occur in for loops when the loop's boundary conditions are not set correctly. This can lead to either skipping the first or last iteration, or accessing an array index out of bounds.
Example:
Example:
int i = 0;
while (i < 10) {
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i <= arr.length; i++) { // Should be i < arr.length
while (i < 10) {
System.out.println(i);
// Missing i++ here leads to an infinite loop
}// Missing i++ here leads to an infinite loop
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i <= arr.length; i++) { // Should be i < arr.length
System.out.println(arr[i]); // This will throw an ArrayIndexOutOfBoundsException
}How do I choose the right loop for my task?
- Use a for loop when:
- You know beforehand how many times you need to iterate.
- You are iterating over a range of values, like indices in an array.
- The loop has a clear initialization, condition, and increment expression.
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}Use a while loop when:
- The number of iterations is not known in advance.
- The loop should continue running until a certain condition is met, which might not be tied to a simple counter.
for
Scanner scanner = new Scanner(System.in );
String input;
while (!(input = scanner.nextLine()).equals("exit")) {
String input;
while (!(input = scanner.nextLine()).equals("exit")) {
System.out.println("You entered: " + input);
}Use a do-while loop when:
- You want to ensure the loop body executes at least once, regardless of the condition.
- The condition is checked after the loop has executed.
int number;
do {
while (number <= 0);
do {
System.out.println("Enter a number greater than 0: ");
number = scanner.nextInt();
} number = scanner.nextInt();
while (number <= 0);
Additional Resources
Cross-Links:
- Control Structures in Java: Explore other control structures in Java, such as if-else statements and switch cases, which are often used in conjunction with loops. Visit Control Structures Page
- Recursion in Java: Learn about recursion, a technique that can sometimes replace loops for certain tasks, with detailed examples and explanations. Visit Recursion Page
- Java Arrays: Understanding arrays is essential when working with loops. Dive into how arrays work and how to iterate through them using loops. Visit Arrays in Java Page
- Java Documentation: Loops: The official Oracle documentation provides comprehensive information about loops in Java, including syntax and examples. Visit Oracle's Java Documentation on Loops
- Java Tutorials on W3Schools: A beginner-friendly guide to loops in Java, complete with interactive examples. Visit W3Schools Java Loops Tutorial
- GeeksforGeeks: Looping in Java: An in-depth article that covers all types of loops in Java with practical examples. Visit GeeksforGeeks Article
You can find examples of loops on the webpage: Loops - basic examples
Previous
|<Selection in Java |
Next
Array in Java >| |