// Nested for loop in Java

import java.util.Scanner;

public class NestedFor {

    public static void main(String[] args) {

        int loopCount = 0;
        
        // Create scanner
        Scanner scanner = new Scanner(System.in);

        // Read number
        System.out.print("Number of integers: ");
        int number = scanner.nextInt();

        // Outer loop
        for (int i = 1; i <= number; i++) {

            System.out.print("The number " + i + " is divisible by:");

            // Inner loop
            for (int j = 1; j <= i; j++) {

                // Divisible by?
                if ((i % j) == 0)
                    System.out.print(" " + j);
                
                // Increment loop count
                loopCount++;
            }
            System.out.println();
        }
        
        // Print loop count
        System.out.println("Loop iterations " + loopCount);
    }
}

© 2012 CS160 Colorado State University. All Rights Reserved.