Introduction to Java using NetBeans

Section 6 : Loops

 

 

A loop is a powerful type of program structure in which a block of statements is repeated over and over.  This process of repetition is referred to as iteration. In some cases the statements are executed a certain number of times, while in other cases the statements are executed until a certain condition is met.  In this activity, you will look at both types of loops.

The for Loop

The for loop repeats a section of code a set number of times. The programmer must know how many times s/he wishes to repeat the block of code.

The programmer must supply three expressions in a for statement:

  • a variable that is set to an initial value
  • a conditional statement that determines when the looping ends
  • an expression that changes the value of the variable with each loop

Syntax (How to use the for Loop):

for (initial value; condition; increment expression) { 
     statement 1; 
     statement 2; 
}

Example Icon Example 1

System.out.println("Counting Up");

for (int i = 1; i <= 5; i++){
     System.out.println(i);
}

This image shows the output window for example 1.
  • The code shown above loops five times.
  • The value of the variable i starts at 1 and ends at 5.
  • The output will be the numbers 1 through 5, each on its own line.

 

Example Icon Example 2

System.out.println("Counting by Fives");

for (int j = 5; j <= 25; j=j+5){
    System.out.println (j);
}

This image shows the output window for example 2.
  • The code shown above loops five times.
  • The value of the variable j starts at 5 and ends at 25.
  • The output will be the numbers 5 through 25, increasing by 5 each time, each on its own line.

 

 

Example Icon Example 3

System.out.println("Counting Down");
for (int j= 10; j>= 0; j--){
    System.out.println (j);
}
  • The code shown above loops 11 times.
  • The value of the variable j starts at 10 and ends at 0.
  • The output will be the numbers 10 down to 0, each on its own line.

This image shows the output window for example 3.

 

 

Using Methods and Passing Parameters

 

 

Assignment 6.1 - Simple Loop

Write a program that:

  1. Accepts input of a starting value.
  2. Accepts input of an ending value.
  3. Displays all the integers (inclusive) between those two values.

Hint: Use a for loop and don't forget to convert the input from a string to an integer.

Sample Output

This shows a possible output for the Fun With Loops program.

Use the ideas from the tutorial to create a GUI. Set the start and end values on the Button and pass the parameters to a method.

Note: to print all values you must add what is already in the label using

label.setText (label.getText() + value)

 

Modify the program so that the user can choose even numbers, odd numbers or all numbers using radio buttons.

To Determine if a number is even or odd use the modulus function which gives you the remainder of a division