# 3 – Loops (Level 3)

## 1 Sample Code

### 1.1 for Loop

```public class ForLoop
{
public static void main (String args [])
{
for (int i = 1; i <6; i++)
System.out.println(i);
}
}
```

### 1.2 while Loop

```public class  WhileLoop
{
public static void main (String args [])
{
int count = 1;
while(count < 6)
{
System.out.println(count);
count++;
}
}
}
```

### 1.3 do while Loop

```import java.util.Scanner;
public class DoWhile
{
public static void main (String args [])
{
Scanner scan = new Scanner(System.in);
do
{
System.out.println("Are we there yet?");
}while(!scan.nextLine().equals("yes"));
System.out.println("Good!");
}
}
```

## 2 Exercises

1. Use a for loop to print the 5 times table up to 12 x 5
2. Use a for loop to print the 7 times table up to 12 x 7 in the form “3 x 7 = 21”
3. Use a for loop to print the following sequence: 0.5, 0.4, 0.3, 0.2, 0.1, 0
4. Use a for loop to print the following sequence: 0.03, 0.02, 0.01, 0, -0.01, -0.02, -0,03
5. Use a for loop to print five random numbers between 1 and 10
6. Use a for loop to print the first ten square numbers: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
7. Use a for loop to print the first ten triangle numbers: 1, 3, 6, 10, 15, 21, 28, 36,45, 55
8. Use a while loop to print the numbers from 1 to 10 inclusive
9. Use a while loop to print the sequence 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1
10. Use a while loop to print the 4 times table up to 12 x 4.
11. Use a while loop to print the 9 times table up to 12 x 9 in the form “1 x 9 = 9, 2 x 9=18… “
12. Prompt the user to enter a number. Keep a running total of the numbers entered. Loop until the user enters -1, exit the loop and print the total
13. Prompt the user to enter a number. Keep a running total of the numbers entered. Loop until the user enters -1, exit the loop and print the average
14. Write a program to test if 91 is prime. Use a while loop to divide 91 by the numbers from 2 to 10. Output True if none of the numbers 91%(number) = 0 for any of the numbers, output False otherwise.
15. Write a program to test if any number is prime. Use a while loop to divide the input by the numbers from 2 to sqrt(input). Output “Prime” if the number is prime, “Not Prime” otherwise.
16. Use a while loop to print the sequence 1, -2, 3, -4, 5, -6, 7, -8
17. Use a while loop to calculate pi using the Liebniz formula pi/4 = 1 – 1/3 + 1/5 – 1/7 + 1/9 – … How many iterations do you need to get 3.141?

This site uses Akismet to reduce spam. Learn how your comment data is processed.