Java for loop used to repeat execution of statement(s) until a certain condition holds true.
for
is a keyword in Java programming language.Java for loop syntax
You can initialize multiple variables, test many conditions and perform increments or decrements on many variables according to requirement. Please note that all three components of for loop are optional. For example following for loop prints "Java programmer" indefinitely.
You can terminate an infinite loop by pressing Ctrl+C.
Simple for loop example in Java
Example program below uses for loop to print first 10 natural numbers i.e. from 1 to 10.
Output of program:
Java for loop example to print stars in console
Following star pattern is printed
*
**
***
****
*****
*
**
***
****
*****
Above program uses nested for loops (for loop inside a for loop) to print stars. You can also use spaces to create another pattern, It is left for you as an exercise.
Output of program:
No comments:
Post a Comment