for
is a keyword in Java programming language.Java for loop syntax
for (/* Initialization of variables */ ; /*Conditions to test*/ ; /* Increment(s) or decrement(s) of variables */) { // Statements to execute i.e. Body of for loop }
// Infinite for loop for (;;) { System.out.println("Java programmer"); }
Simple for loop example in Java
Example program below uses for loop to print first 10 natural numbers i.e. from 1 to 10.//Java for loop program class ForLoop { public static void main(String[] args) { int c; for (c = 1; c <= 10; c++) { System.out.println(c); } } }
Java for loop example to print stars in console
Following star pattern is printed*
**
***
****
*****
class Stars { public static void main(String[] args) { int row, numberOfStars; for (row = 1; row <= 10; row++) { for(numberOfStars = 1; numberOfStars <= row; numberOfStars++) { System.out.print("*"); } System.out.println(); // Go to next line } } }
OUTPUT
Post a Comment
Click to see the code!
To insert emoticon you must added at least one space before the code.