Java for Loop

In computer programming, loops are used to repeat a specific block of code until a certain condition is met (test expression is false). For example, imagine we need to print a sentence 50 times on your screen. Well, we can do it by using the print statement 50 times (without using loops). How about you need to print a sentence one million times? You need to use loops. With loops, we can simply write the print statement one time and run it for any number of times. It's just a simple example showing the importance of loop in computer programming. The syntax of for Loop in Java is:


\begin{lstlisting}
for (initialization; testExpression; update)
{
// codes inside for loop's body
}
\end{lstlisting}

Steps involving in working of for loop.

  1. The initialization expression is executed only once.
  2. Then, the test expression is evaluated. Here, test expression is a boolean expression.
  3. If the test expression is evaluated to true, codes inside the body of for loop is executed. Then the update expression is executed. Again, the test expression is evaluated. If the test expression is true, codes inside the body of for loop is executed and update expression is executed. This process goes on until the test expression is evaluated to false.
  4. If the test expression is evaluated to false, for loop terminates.


\begin{lstlisting}
// Program to print a sentence 10 times
\par
class Loop {
pu...
... 1; i <= 10; ++i) {
System.out.println(''Line '' + i);
}
}
}
\end{lstlisting}

Output


\begin{lstlisting}
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
\end{lstlisting}

In the above example, we have

Here, initially, the value of i is 1. So the test expression evaluates to true for the first time. Hence, the print statement is executed. Now the update expression is evaluated. Each time the update expression is evaluated, the value of i is increased by 1. Again, the test expression is evaluated. And, the same process is repeated. This process goes on until i is 11. When i is 11, the test expression (i <= 10) is false and the for loop terminates.


\begin{lstlisting}
// Program to find the sum of natural numbers from 1 to 1000....
...um = sum + i
}
\par
System.out.println(''Sum = '' + sum);
}
}
\end{lstlisting}

Output for the above code will be Sum = 500500.



Subsections