Introduction to Java For Loops

Posted By: Java Examples - 10:28 AM

Share

& Comment

Purpose :
The for statement is similar to the while statement, but it is often easier to use if you are counting or indexing because it combines three elements of many loops: 
initialization, testing, and Increment.


Initialization: It allows the variable to be initialize. Such as: int i = 0; int j = 2; 
Termination (or condition): It allows to check the certain condition. If condition is true then all statements and processes written in the for block will be executed otherwise ignored. Condition such as: i <= 5; i <j; 
Increment: It allows the how much increase the given variable. Such as: i++; j++;


General Form :
The for and equivalent while statements have these forms :
for (initial-statement; condition; next-statement) {
    body
}

Example  :
Printing a table of factorial between 1 to 10
/**
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package loop;

/**
 *
 * @author ACHCHUTHAN
 */
public class Factorial {

    public static void main(String[] args) {
        int limit = 10;
        int factorial = 1;

        for (int i = 1; i <= limit; i++) {
            factorial = 1;

            for (int factor = 2; factor <= i; factor++) {
                factorial *= factor;
            }
            System.out.println(i + "! is : " + factorial);
        }
    }
}

Output of this program :

run:
1! is : 1
2! is : 2
3! is : 6
4! is : 24
5! is : 120
6! is : 720
7! is : 5040
8! is : 40320
9! is : 362880
10! is : 3628800
BUILD SUCCESSFUL (total time: 1 second)

About Java Examples

I’m passionate about Web Development and Programming and I go to extreme efforts to meet my passion. I’m a believer of learning the fundamentals first. I try to understand everything little bit more than the average.

Copyright © 2016 Java Examples ACHCHUTHAN.ORG. Designed by Templateism .