The for loop

Let's see how the for loop works. The for loop is one of the most commonly used loops in Java programs, and it it is very important to understand how it works internally. So, let's say we want to print the numbers from 1 to 100 using the forloop. For the syntax to execute the numbers from 1 to 100 in a sequence and to write that in a for loop, we will simply write:

// 1 to 100

/* for(initialization;condition;increment)
{
} */
for (int i=0;i<100;i++)
{
system.out.println(i);
}
}

Since we want to print 0, 1, 2, 3, we use i++. This means for every loop, it increments only by  1. And while looping, each time, it also checks whether the preceding condition is satisfied. So, if 1 is less than 100, it goes inside; if 2 is less than 100, it goes inside. Until this condition is satisfied, it will keep on looping. When the value of i reaches 100, 100 is less than 100, which is false. At that time, it terminates the loop and comes out of it. We will use a basic example here:

for (int i=0;i<5;i++)
{
system.out.println(i);
}

To run test cases in debug mode in the IDE, double-click at the location shown in the following screenshot:

Line from which the debugging begins

When you see the blue icon, run that in the debug mode by clicking the insects-like symbol. It will ask you to launch in debug mode. Just click on Save to do so:

Debug icon at the top of the editor

You will see all the variable values here. Step by step, we'll go inside the loop, and will execute the next step of the program:

Variable value while debugging

Finally, when it reaches the value 4, and is incremented by 1 again, it is 5. Note that it comes out of the loop without going inside that after the value becomes 5. So, that means the condition is no longer satisfied and the loop will run five times. The output is shown in the following screenshot:

Final output as per the code

So, that's how the for loop works.

Now, if we set the condition to the following, it will not go inside the for loop, even for the first time since, the condition is false.:

for (int i=5;i<3;i++)

On running the preceding condition in in the debug mode, the complete loop is skipped,and nothing is seen in the output.

Let's see another example:

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

The output will be:

0
2
4
6
8

This is how the for loop works internally.

In the next section, we will learn about the if...else and do...while loops. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.87.156