Java for Loop Statements with Programming Examples

loops:

Java for loop statement with programming examples:- Another group of commands to control the sequence set the so-called Repeat instructions or loops. Like the names of these statements make it clear that an instruction or a block can be used statements several times in a row.

java for loop statement:

The first representative of these loops is the for loop statement. Their syntax is:

In this case, the initialization one or more (identical) variables, and then the expression whose result type must be of type boolean. Is value true, the statement or statement block (also called the hull) and then the instructions in the update list (a list of commands). This will be repeated as long as: until the expression returns false. Here is an example:

for (int i = 0; i <10; i ++)

System.out.println (i);

This program symbol does nothing other than the numbers 0 to 9 line by line on the screen. How does it work? First, the initialization statement int i = 0; , i.e. variable i is declared and initialized with the value 0. Next, the expression i < 10 evaluates – this returns true because i just has the value 0, the statement System.out.println(i); is thus executed and prints the number 0 the screen. Now the update statement i++ is executed, which increases the value of i by one, and then again the expression i < 10, which returns true as a result – the statement System.out.println(i); thus comes to execution again. This game continues until the expression i < 10 returns the result false, which is the case for the first time exactly when the variable i assumes the value 10, to which the statement System.out.println(i); no longer and the loop is terminated. The following loop can be programmed analogously to this example.

for (int i = 9; i >= 0; (i—)

System.out.println(i);

Here now, you can guess, the numbers 0 to 9 on the screen again, but this time in reverse order. It should be noted that – as with if-else-statements – it is also here it is useful to always clip the statements belonging to the loop as a block, even if there is only one statement to make possible confusion prevention.

The loop is executed in the following steps:

  • Initialization is performed at the beginning of the java for loop. On this You can specify multiple commas separated by commas in the following.
  • Then it is tested whether the condition is satisfied. If so, the commands of the java for loop body are executed. Otherwise, the loop is aborted. (In the case of a java for loop, it happens that the inside of the loop is never reached.)
  • After the java for loop body, the increment command is executed. Normally, the java for loop variable is increased here (i++) or Rear-formulated sops are reduced accordingly. Also here allows you to separate multiple commands by commas. Then it goes on to the second point of this list, so the Test the condition.



A simple example of java for loop looks like this:

The above java for loop outputs the values 0 to 9, but no more than 10! The condition is yes i<10. Therefore, the loop is terminated as soon as i 10 achieved. The above example does without the curved brackets. This is permissible here because the grinding body is only made from a single instruction As with if, my recommendation is: accustom Make sure you always set curved brackets! The following loop is also syntactically correct. Here, during initialization x and y. With each loop pass x is increased by 10 and y by 20 – and this until the sum of the two variables is greater than or equal to 1000 for the first time.

The initialization, condition, and increment expressions are optional. for(;;) is thus permitted and provides an endless loop, if it does not end with the break.

Attention, trap!

For(…) is followed by the command executed in the loop should. Multiple commands must be combined with { and } to form a block in the following. Be careful, however, that after for(…) you do not Specify the semicolon. Java interprets the semicolon as an empty command, that is executed according to the loop. The output of the following program lines is therefore simply 10. Numbers 0 through 9 are not output. The reason: First, the Processed loop for i=0 to i=9. The semicolon shall be regarded as the loop body after the for – i.e. an empty command. Finally, it runs i++. I then has the value 10, the java for loop is aborted because of the condition i<10. Only now is the first and only one-time printout run!

variable declaration within the java for loop:

The variables occurring in the loop must be prefixed like all other variables. Alternatively, Java also allows the Declaration directly in the initialization expression. In this case, all variables declared with the same type:

Both loops are processed correctly and equally. However, in the left code example, the variable i is still after the loop at your disposal. It is now 10. For the right example, you can i, on the other hand, only use within the loop. Behind the }, which ends the loop body, i is no longer accessible!


Examples

The java for loop is one of the most elementary and most important language elements from Java. Your syntax must be fully trusted. You need to know which of the three parameters has what meaning and whether you formulate the condition with < or >. I have two more here Samples, each with a short explanation. The following Loop counts from 100 backwards to 0, and in steps of ten:

Do you know how large the sum of all numbers is from 1 to 1000, that is 1 + 2 + 3? + . . + 1000? There is a nice formula for this (search in Wikipedia by the Gaussian formula), but if you do not memorize the formula You know, you can run Java, right? Note that You must declare and initialize the sum variable before the loop. sum+=i is the shorthand for sum = sum + i. The result is only issued after the end of the loop with println – we want do not see all interim results!

java For loops for floating-point numbers:

In principle, the java for loop variable can also be of the double data type:

However, floating point loop variables are extremely problematic. I have already pointed out that for every calculation with floating point numbers tiny rounding errors occur. Different from a java for loop, it is not clear in advance which end value the loop of the European Union. The following loop should count from 0 to 2 and the loop variable increase by 0.1 with each pass. It would therefore be expected that the Loop outputs the values 0, 0,1, 0,2 up to 2,0. But that’s not the case. The loop ends at 1.9.

That x assumes the number 0.30000000000000000000004 instead of 0.3 is here is not the problem – this deviation is so small that it rarely disturbs. But that the loop never reaches the targeted end value, can have serious consequences. A simple solution is to End value simply a little more generously to formulate – here with 2,001 instead of 2.0:

Personally, I prefer it in almost all cases, in java for loops with integer variables. The following lines show two variants, with guaranteed to pass through all values between 0 and 2 in steps of 0.1 in the following. The first variant is somewhat more compute-intensive (a floating-point multiplication for each loop pass), but less susceptible to rounding errors.


Nested for loops in java:

Java for loops, like all other procedural language elements, can be (if, switch, while, do-while). In this case, Java with the execution of the outer loop and then leads at each loop pass the complete inner loop out.

The simplest way to understand this is to use an example: The following Program outputs a 1×1 table on the screen. The outer The loop for the variable i is executed for each row. Within each The internal loop for the variable j is executed on the line. It shall: column by column, where print instead of print to avoid line breaks. Each output is the tab character \t to create a simple column formatting.

The output of the program is as follows:

java for loop

Infinite java for loop:

You can write a loop with an empty body. Thus, the two constructions:

are syntactically correct. They represent infinite loops of empty bodies (remember that when the second expression is missing, it is considered as true). In practice, they are of no interest. However, this construction

for (; ; ) instruction

is an infinite loop that can eventually be output by a break statement.



java for-each loops:

Java also knows so-called for-each loops. The loop variable in turn, all the elements of an enumeration. As enumeration various data are possible, but you are not all yet have met: arrays, collections, and any other Objects whose class implements the Iterable interface. The idea of the for-each loop will but easy to understand. The book will continue to follow various other examples. Unlike some other programming languages, the Java Developer the keyword foreach avoided. for-each loops are as conventional loops are formed with for and differ only in syntax: Type of loop variable must be specified. It is not allowed to use a loop variable that of the java for loop. Then follow the variable name and finally after a colon the enumeration object:

caution

For multi-dimensional arrays, a for-each loop only passes through the Array elements of the first dimension. This is itself around arrays. This is because multi-dimensional arrays in Java are simply arrays of arrays.

 for vs for-each:

for-each loops are ideal for all elements of an array or to read and process in any form a list, so to spend, to sum etc. Caution is however required if you want to modify the elements of an array or enumeration. For elementary data types, the loop variable contains a copy of the enumeration. Changes to the loop variables therefore have no Influence on the content of the enumeration. For such tasks: Use a conventional java for loop.


java for loop statement Examples:

example: how to use nested for loops in java:

output:

java for loop

Example: how to make Pyramid in java using nested for loops:

output:

java for loop


Example: how to make an inverted Pyramid in java using nested for loops:

output:

java for loop

Example: how to use for each loop in java:

output:

java for loop



Example: how to use infinite for loop in java:

output:

java for loop

The loop will never stop until you press the ctrl+c

Example: how to find the sum of the first 10 natural numbers:

output:

java for loop


related Article:

Java Switch Statement with Programming Examples

Java if Statement: if else, correct indentation, ternary operator, nested if

 

 

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: