answersLogoWhite

0

How do you work loop in java?

Updated: 8/9/2023
User Avatar

Wiki User

10y ago

Best Answer

A for loop works similarly to most programing languages. An example of a for loop is

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

{

}

The code you want to be operated every loop should be between the brackets. The first part of a for loop is the declaration. The second part, is the comparison used to determine if the loop should continue, and the third part is what operation should be done after every loop.

The Basic for Loop

The for loop is especially useful for flow control when you already know how many times you need to execute the statements in the loop's block. The for loop declaration has three main parts, besides the body of the loop:

• Declaration and initialization of variables

• The boolean expression (conditional test)

• The iteration expression

The three for declaration parts are separated by semicolons. The following two examples demonstrate the for loop. The first example shows the parts of a for loop in a pseudocode form, and the second shows a typical example of a for loop.

for (/*Initialization*/ ; /*Condition*/ ; /* Iteration */) {

/* loop body */

}

Ex:

for (int i = 0; i<10; i++) { System.out.println("i is " + i); }

The Basic for Loop: Declaration and Initialization

The first part of the for statement lets you declare and initialize zero, one, or multiple variables of the same type inside the parentheses after the for keyword. If you declare more than one variable of the same type, then you'll need to separate them with commas as follows:

for (int x = 10, y = 3; y > 3; y++) { }

The declaration and initialization happens before anything else in a for loop. And whereas the other two parts-the boolean test and the iteration expression-will run with each iteration of the loop, the declaration and initialization happens just once, at the very beginning. You also must know that the scope of variables declared in the for loop ends with the for loop! The following demonstrates this:

for (int x = 1; x < 2; x++) { System.out.println(x); // Legal } System.out.println(x); // Not Legal! x is now out of scope If you try to compile this, you'll get something like this: Test.java:19: cannot resolve symbol symbol : variable x location: class Test System.out.println(x); ^

Basic for Loop: Conditional Expression

The next section that executes is the conditional expression, which (like all other conditional tests) must evaluate to a boolean value. You can have only one logical expression, but it can be very complex. Look out for code that uses logical expressions like this:

for (int x = 0; ((((x < 10) && (y-- > 2)) | x == 3)); x++) { }

The preceding code is legal, but the following is not:

for (int x = 0; (x > 5), (y < 2); x++) { } // too many //expressions The compiler will let you know the problem: TestLong.java:20: ';' expected for (int x = 0; (x > 5), (y < 2); x++) { } ^ The rule to remember is this: You can have only one test expression. In other words, you can't use multiple tests separated by commas, even though the other two parts of a for statement can have multiple parts.

Basic for Loop: Iteration Expression

After each execution of the body of the for loop, the iteration expression is executed. This is where you get to say what you want to happen with each iteration of the loop. Remember that it always happens after the loop body runs! Look at the following:

for (int x = 0; x < 1; x++) { // body code that doesn't change the value of x } The preceding loop executes just once. The first time into the loop x is set to 0, then x is tested to see if it's less than 1 (which it is), and then the body of the loop executes. After the body of the loop runs, the iteration expression runs, incrementing x by 1. Next, the conditional test is checked, and since the result is now false, execution jumps to below the for loop and continues on. Keep in mind that barring a forced exit, evaluating the iteration expression and then evaluating the conditional expression are always the last two things that happen in a for loop! Examples of forced exits include a break, a return, a System.exit(), or an exception, which will all cause a loop to terminate abruptly, without running the iteration expression. Look at the following code: static boolean doSomething() { for (int x = 0; x < 3; x++) { System.out.println("in for loop"); return true; } return true; } Running this code produces in for loop The statement only prints once, because a return causes execution to leave not just the current iteration of a loop, but the entire method. So the iteration expression never runs in that case. Basic for Loop: for Loop Issues None of the three sections of the for declaration are required! The following example is perfectly legal (although not necessarily good practice): for( ; ; ) { System.out.println("Inside an endless loop"); } In the preceding example, all the declaration parts are left out so the for loop will act like an endless loop. For the exam, it's important to know that with the absence of the initialization and increment sections, the loop will act like a while loop. The following example demonstrates how this is accomplished: int i = 0; for (;i<10;) { i++; //do some other work } The next example demonstrates a for loop with multiple variables in play. A comma separates the variables, and they must be of the same type. Remember that the variables declared in the for statement are all local to the for loop, and can't be used outside the scope of the loop. for (int i = 0,j = 0; (i<10) && (j<10); i++, j++) { System.out.println("i is " + i + " j is " +j); } The last thing to note is that all three sections of the for loop are independent of each other. The three expressions in the for statement don't need to operate on the same variables, although they typically do. But even the iterator expression, which many mistakenly call the "increment expression," doesn't need to increment or set anything; you can put in virtually any arbitrary code statements that you want to happen with each iteration of the loop. Look at the following: int b = 3; for (int a = 1; b != 1; System.out.println("hii")) { b = b - a; } The preceding code prints hii hii

User Avatar

Wiki User

13y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

12y ago

"For loops are typically used when the number of iterations is known before entering the loop."

for (int i = 1; i <= 10; i++){

System.out.println("Hello World");

}

In this line of code we are saying to the compiler. As long 'i' (1) is less than equal to 10, run the following statement 10 times, and after each run, increment the variable 'i' by 1 "i++".

Result of this code will produce 10 lines with text saying "Hello World".

This answer is:
User Avatar

User Avatar

Wiki User

10y ago

Loops in java are used so you don't have to write the same code over and over again. A basic example of this would be using for(int i = 0; i < 4; i ++){ system.out.println("example"); } instead of writing system.out.println("example"); four times yourself

This answer is:
User Avatar

User Avatar

Wiki User

8y ago

In normal words if you want to run several commands over and over unless you get your desired result is called loops.

in other words, a loop is a sequence of instructions that is continually repeated until a certain condition is reached. Typically, a certain process is done, such as getting an item of data and changing it, and then some condition is checked such as whether a counter has reached a prescribed number. If it hasn't, the next instruction in the sequence is an instruction to return to the first instruction in the sequence and repeat the sequence. If the condition has been reached, the next instruction "falls through" to the next sequential instruction or branches outside the loop. More info

java.about.com/od/l/g/Loops.htm

marcus-biel.com/loops-in-java/

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

The enhanced for loop, new to Java 6, is a specialized for loop that simplifies looping through an array or a collection. In this chapter we're going to focus on using the enhanced for to loop through arrays. We'll revisit the enhanced for as we discuss collections in the future chapter.

Instead of having three components, the enhanced for has two.

for(declaration : expression)

The two pieces of the for statement are

• declaration The newly declared block variable, of a type compatible with the elements of the array you are accessing. This variable will be available within the for block, and its value will be the same as the current array element.

• expression This must evaluate to the array you want to loop through. This could be an array variable or a method call that returns an array. The array can be any type: primitives, objects, even arrays of arrays.

Using the above definitions, let's look at some legal and illegal enhanced for declarations:

String [] sNums = {"one", "two", "three"};

// legal 'for' declarations

for(String s : sNums) ; // loop thru the array of Strings

The enhanced for loop assumes that, barring an early exit from the loop, you'll always loop through every element of the array. The following discussions of break and continue apply to both the basic and enhanced for loops.

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

The for loop is especially useful for flow control when you already know how many times you need to execute the statements in the loop's block. The for loop declaration has three main parts, besides the body of the loop:

• Declaration and initialization of variables

• The boolean expression (conditional test)

• The iteration expression

The three for declaration parts are separated by semicolons. The following two examples demonstrate the for loop. The first example shows the parts of a for loop in a pseudocode form, and the second shows a typical example of a for loop.

for (/*Initialization*/ ; /*Condition*/ ; /* Iteration */) {

/* loop body */

}

Ex:

for (int i = 0; i<10; i++) { System.out.println("i is " + i); }

This answer is:
User Avatar

User Avatar

Wiki User

9y ago

"if" is not a loop. The basic syntax of an "if" statement is:

if (condition)

{

//commands

}

Or:

if (condition)

{

// commands if true

}

else

{

// commands if false

}

This answer is:
User Avatar

User Avatar

Wiki User

8y ago

In computer programming, a "loop" is a structure that allows you to repeat the same commands several times. Loops in Java include the "while" structure, the "do ... while" structure, and the "for" structure.

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

In for loop, execution of a group of statements is repeated a designated number of times

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: How do you work loop in java?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering
Related questions

How do you exit in nested loop in java?

You may exit a nested loop in Java using a break with a label for the outer loop.


What are functions in JAVA?

for loop function


When is Iteration used in a Java program?

in a loop


How can you repeatedly execute a code in java script?

1) use for loop 2) do while loop


Which Loop avoids check at every iteration?

All loops available in Java (for, while, do-while) have a loop termination condition that would get executed during every iteration of the loop. Without checking the loop condition the loop cannot be terminated and hence avoiding the loop condition check during iteration is not logic and Java does not do it.


Which loop is also called an exit-condition loop in C programming?

The do while loop is also called an exit condition loop in c, c++, and java.


What is a nested loop in java?

A nested loop is a (inner) loop that appears in the loop body of another (outer) loop. The inner or outer loop can be any type: while, do while, or for. For example, the inner loop can be a while loop while an outer loop can be a for loop.


Write a c program Fibonacci series using for loop in java?

Exactly what do you mean by 'C program in Java'


What are various loops available in java?

Java has three kinds of loops 1. For Loop 2. While Loop 3. Do - While Loop Both For loop and While loop would iterate through a certain lines of code within the loop's limit as long as the loop condition is satisfied. A do while loop would execute the loop once even before checking the condition. So in a do while loop, even if the loop condition is not satisfied the loop would execute once. Example Declarations: for(int i = 0; i &lt; n; i++) { ..... } while (i &lt; n) { ... i++; } do { ... i++; } while (i &lt; n) ;


Why do you use the loops in java?

You use loops in Java when you want a set of actions to be repeated until a particular condition is met or for a certain number of times.The different types of loops in Java are:For LoopsDo-While LoopsWhile Loops


What are control structures used in javascript?

The control structures used in java script are if-statement, for-loop, for-in loop, while loop,do-while loop, switch-statement, with-statement. try-catch-finally statements.


How does java command while true work?

The contents of a while loop will always execute if the statement between the while parentheses resolves to a boolean true. Hence, if you place "true" as the while statement, the loop will execute forever (until the loop is forcefully broken or the computer or process shuts down).