## Loops in the programming language JAVA

*Introduction to loops (cycles)*

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");

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

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:

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:

for (initialization; condition_trap; expression_of_the_loop)

{

string_order;

}

{

string_order;

}

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 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:

The loop condition is a logical expression that can be either true or false.

The cycle will be repeated as long as this condition is fulfilled. When during a cycle they are variable and do not change, and we can change it through the loop, the condition would always be fulfilled, 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_pet and this is usually a form expression

This means that in the memory space and the new value is 1 higher than the previous one. For the cycle now looks like:

**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:

**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 fulfilled. When during a cycle they are variable and do not change, and we can change it through the loop, the condition would always be fulfilled, 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_pet and this is usually a form expression

**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", 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

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

**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**
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:

<div class="moj_kod">

sum = sum + 1;<br>

sum = sum + 2;<br>

sum = sum + 3;<br>

sum = sum + 4;<br>

...<br>

sum = sum + i;<br>

...<br>

sum = sum + 10;<br>

</div>

sum = sum + 1;<br>

sum = sum + 2;<br>

sum = sum + 3;<br>

sum = sum + 4;<br>

...<br>

sum = sum + i;<br>

...<br>

sum = sum + 10;<br>

</div>

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 picture below.

And after launch:

And after launch:

*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.*While loop with a condition at the beginning*

In general, the cycle looks like:

while (condition_of_the_loop)

{

string_order;

}

{

string_order;

}

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;

int score;

int totalScore=0;

int totalScore=0;

Points will be loaded through the cycle and added to the total number of points:

while(totalScore < 30 )

{

scoreStr =JOptionPane.showInputDialog(“Load the measured temperature”);

score= Integer.parseInt(scoreStr);

totalScore= totalScore+ score;

}

{

scoreStr =JOptionPane.showInputDialog(“Load the measured temperature”);

score= Integer.parseInt(scoreStr);

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;

while (totalScore <30)

{

scoreStr = JOptionPane.showInputDialog ("Load measured temperature");

score= Integer.parseInt (NumberBodStr);

totalScore = totalScore + score;

numberCycle ++; // Increases the number of cycles by 1

}

int totalScore = 0;

int numberCycle = 0;

while (totalScore <30)

{

scoreStr = JOptionPane.showInputDialog ("Load measured temperature");

score= Integer.parseInt (NumberBodStr);

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

expand with additional condition

totalScore <30

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 with the condition in the end*

CIKLUS 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:

do

{

a_set_of_commands;

}

while(loop_condition);

{

a_set_of_commands;

}

while(loop_condition);

This practically means that in the

Let's look at the following example:

**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:

*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:

double temperature;

String temperatureStr;

String temperatureStr;

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

{

temperatureStr = JOptionPane.showInputDialog ("Load measured temperature");

temperature = Double.parseDouble (temperatureStr);

}

while (temperature != -100);

{

temperatureStr = JOptionPane.showInputDialog ("Load measured temperature");

temperature = Double.parseDouble (temperatureStr);

}

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

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 ((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) + " ");**## EXAMPLES FOR INDEPENDENT WORK

**Example for stand-alone work 1:**

Determine for how many years the stake in the bank from U dinar with the annual interest rate P% rises to R dinars

**Example for standalone work 2:**

Write a program that creates a translation table from the Celsius scale in the Farenhain scale for values c1 to c2 degrees with step 1C (F = 1.8 * C + 32).

**Example for stand-alone work 3:**

The Athlete had planned to run A kilometers during the N Day Preparation Day, and each subsequent 10% more than the previous day's norm. Make a table from which you can see each day preparing how many athletes need to run and how much they will run in the course of preparation. .

**Example for stand-alone work 4:**

Write a program that transforms the number N by removing it from the right to the right. For example, 12000 are transformed into 12.

**Example for stand-alone work 5:**

Make a mini-bill by month. Load monthly earnings. For each day, write down how much money you have spent (one cycle). Read the interruption when less than 10 dinars are left of the total salary. If you have entered the minus print a message about it. Print the number of days you spent money.

**Example for stand-alone work 6:**

Data is the target of N concentric circles of the diameters r = 1,2, ..., 10 and point A (x, y) in meta. To score in the smallest round gets 10 points, and for each next ring one is less. Write program that determines how much points are scored gets to hit A, if the player is the target and the start of the game. systems match?

**Example for stand-alone work 7:**

In the vessel is contained in liters of p% salt solution. from the vessel, a liter of mixture is poured out and a liter of clean water is added, after which the solution is mixed. If N times are "casting" and "stuffing", write a program that prints the salt concentration table in the court after each "casting" and "filling."

Example for stand-alone work 8:

Example for stand-alone work 8:

Load the number of elements of a set n and class k, and then specify the number of variations of n elements of the k. class.

**Example for stand-alone work 9:**

Print the multiplication table.

**Example for stand-alone work 10:**

Create a program that determines the smallest common content of two loaded integers.