This lesson is being piloted (Beta version)

Loops in Java

Overview

Teaching: 30 min
Exercises: 30 min
Questions
  • How do you use loops in Java?

  • How do you use if statements in Java?

Objectives
  • Understand the control flow constructs available in Java.

  • Apply a range of conditional logic and loops to solve a variety of problems.

Pi j1.4 loops from mcollison

A common requirement in programming is to repeat an operation several times. A good way to achieve this in Java is with a for loop. To repeat something, say, 10 times you can use the following construct:


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

This code prints the numbers 0, 1, 2, …, 9 on separate lines. Here the loop variable ‘i’ is set equal to 0 and the print statement executed; it is then set equal to 1 on the next iteration of the loop and the print statement executed again; this continues until ‘i’ is 10 at which point the loop terminates without printing that value.

Loop exercises 

  1. Create a program ‘PrintN.java’ that takes two command-line arguments; assume the first argument is a word and the second argument a number. Print the word of the first argument the second argument number of time. Use a ‘for’ loop to write this version of this function.

Here is an example of the output you should expect:

$ java PrintN Hello 3
Hello
Hello 
Hello 

Solution link

  1. Earlier you adjusted a while loop in GreenBottles.java to change the number of iterations. Adapt the GreenBottles.java program to use a for loop instead of a ‘while’ loop.

Solution link

  1. Write a program FactorialLessThan1m that, given a number num, calculates the factorial by multiplying the numbers 1, 2, 3, … , n and prints the value only if it is less than 1,000,000 otherwise it prints None.

Solution link

  1. Given the array of integer numbers intArr below, write a program Squeeze.java that uses a for each loop and prints a list where all adjacent elements that are the same have been reduced to a single element, so squeeze([1, 2, 2, 3]) returns [1, 2, 3].

int[] intArr = { 1, 2, 2, 2, 3, 4, 4 ,5 }

Solution link

  1. Write a program SumPowers, that finds the sum of the first n natural numbers raised to the pth power; that is it prints the sum:

    1p+2p+3p+…np

Take the first command-line argument as n and the second command-line argument as p.

Solution link

Key Points

  • Java is a general purpose, high-level, compiled, strongly typed, object oriented programming language