Loops in Java

While Loop

A loop allows us to execute a block of statements multiple times. The following is a while loop printing out values from 0 to 9.

int i = 0;
while (i < 10)
{
  System.out.println(i);
  i++;
}

When we run the code, the condition is first evaluated. If it is true, the body of the loop will be executed, and the condition is checked again; if the condition is false, the body is skipped.

The factorial function of a positive integer n is defined as
n! = n * (n-1) * … * 2 * 1.

Below is a class FactorialWhile which takes an input integer from command-line arguments and outputs its factorial.

public class FactorialWhile
{
  public static void main(String[] args)
  {
    int   num = Integer.parseInt(args[0]);
    long  factorial = 1;
    int   i = 1;
    while (i <= num)
    {
      factorial *= i;
      i++;
    }
    System.out.println(factorial);
  }
}

Here args[0] refers to the first argument in the command line. For example, when we use the following command to run the program, args[0] stores the string “10”;

    $java FactorialWhile 10

The method parseInt() of the class java.lang.Integer converts a string into an integer.
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)

A loop can be defined in the body of another loop; this is called nested loop. The following example uses nested loops to print out lines of “*” in a triangle shape.

public class StarsWhile
{
  public static void main (String[] args)
  {
    int	rows = Integer.parseInt(args[0]);
    int	i = 0, j = 0;
    while (i < rows)
    {
      j = 0;	// Don’t miss this initialization
      while (j <= i)
      {
        System.out.print("*");
        j++;
      }
      System.out.println();
      i++;
    }
  }
}

The program can be run using the following command:

	$java StarsWhile 4

It will print out results as below.

	*
	**
	***
	****

For Loop

The following is a for loop printing out values from 0 to 9.

for (int i = 0; i < 10; i++)
  System.out.println(i);

The header of a for loop has three parts:

  • initialization, executed once before the loop starts,
  • boolean condition, evaluated in each iteration,
  • increment, executed at the end of each iteration.

While loops and for loops can be converted to each other equivalently. The following class FactorialFor computes the factorial function.

public class FactorialFor
{
  public static void main(String[] args)
  {
    int num = Integer.parseInt(args[0]);
    long factorial = 1;
    for (int i = 1; i <= num; i++)
      factorial *= i;
    System.out.println(factorial);
  }
}

The following example uses nested for loops to print out stars in a triangle shape.

public class StarsFor
{
  public static void main(String[] args)
  {
    int rows = Integer.parseInt(args[0]);
    for (int i = 0; i < rows; i++)
    {
      for (int j = 0; j <= i; j++)
        System.out.print("*");
      System.out.println();
    }
  }
}

Comments

comments