Bringing the if...else condition in the for loop

Now, let us bring the if...else condition into the for loop. Let's add the following to our code:

for (int i=0;i<10;i=i+2)
{
if(i==8)
system.out.println("print 8 is displayed");
else
system.out.println("I did not find");
}

Since there is only one statement here, we won't be writing it in the braces. Now, let's analyze this. The values will begin to enter the for loop from zero until the value is less than 10.

On entering the for loop, it will check if the first value, 0, is equal to 8. Since it is not equal, it will display "I didnot find". Now, for the second time, 2 will be added to 0 (as per our set condition). Notice that this new value is still not equal to 8; hence the output will remain same for values 0, 2, 4, and 6. Next, when 8 goes inside the for loop, the condition is satisfied and the " 8 is displayed" statement is displayed as the output: 

"8 is displayed" and "I didnot find" is displayed as the output

Now, if we say i=9, it will never be printed because the condition we set is i+2, which will be an incremental even number. This means that the condition is not satisfied and the very next step after the if condition is not executed. Thus, we can say that, if a condition is true, only then will it be executed; if not, the conditions or the statements present in the else block will be executed. And when you run this, you always get the output as "I did not find"

However, if we write the following syntax, we will get the output as "9 is displayed":

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

This is how the if...else condition works using the for loop. In the next section, we will learn about for loops in detail. 

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

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