Examples

This section includes three examples of full programs using loops.

Example 1: smallest of 10 numbers

In this example, we will ask the user for 10 numbers and then print out the smallest number entered.

import java.util.*;
public class Example1 
{
    public static void main(String[] args) 
    {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter 10 numbers.");
        System.out.println("Press Enter after each one.");

        int min = s.nextInt();
        for (int i = 1; i < 10; i++) 
        {
            int next = s.nextInt();
            if (next < min) min = next;
        }
        System.out.printf("Smallest: %d%n", min);
    }
}

Example 2: compute an exponent

In the next example, we will use a loop to help compute an exponent. We will ask the user for the base (b) and the exponent (n), and will compute and print $b^n$.

import java.util.*;
public class Example2 
{
    public static void main(String[] args) 
    {
        Scanner s = new Scanner(System.in);
        System.out.print("Enter base: ");
        int b = s.nextInt();
        System.out.print("Enter exponent: ");
        int n = s.nextInt();

        int exp = 1;
        for (int i = 0; i < n; i++) 
        {
            exp *= b;
        }
        
        System.out.printf("%d^%d = %d%n", b, n, exp);
    }
}

Example 3: compute factorials

In this example, we will ask the user for a positive integer bound (we’ll call it n). Then, we will calculate and print:

1!
2!
...
n!

The ! means factorial. For example, 5! is calculated as follows:

5! = 5*4*3*2*1 = 120

This will require a nested loop. The outer loop will step through the numbers from 1 to n, and the inner loop will find the factorial of the current number.

import java.util.*;
public class Example3 
{
    public static void main(String[] args) 
    {
        Scanner s = new Scanner(System.in);
        System.out.print("Enter a positive integer bound: ");
        int bound = s.nextInt();

        if (bound >=1) 
        {
            for (int i = 1; i <= n; i++) 
            {
                int fact = 1;
                for (int j = i; j >= 1; j--) 
                {
                    fact *= j;
                }
                System.out.printf("%d! = %d%n", i, fact);
            }
        }
        else 
        {
            System.out.println("Bound must be positive.");
        }
    }
}