Java Course 5: for Loops

Print the numbers 1 to 9

(look very carefully at the semi colons below!)

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

Print the numbers 1 to 10

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

Print the numbers 10 to 1

for(int i= 10 ; i>0; i=i-1) {
    System.out.println(i);
}

Prints the first ten squared numbers in the form “3 squared = 9”

for(int i =1; i<=10; i =i+1) {
    System.out.println(i+ " squared = "+ i*i);
}

Nested for loops

The following nested for loops print out the pattern triangle pattern below. Note the j<i condition in the second for loop and the use of print() and println().

for(int i = 0; i < 6; i++) {
	   for(int j = 0; j < i; j++) {
	       System.out.print("*");
	   }
	   System.out.println("");
}
*
**
***
****
*****

Exercise

Use for loops to print out the following:

  1. Numbers from 1 to 70 inclusive
  2. Numbers from 10 to -10 inclusive
  3. Odd numbers from 1 to 19 inclusive
  4. Even numbers from 10 to -20 inclusive
  5. The sequence 0.3, 0.4, 0.5, 0.6, 0.7
  6. The sequence 0.1, 0, -0.1, -0.2, -0.3
  7. The square numbers 1, 4, 9, 16, … 81, 100
  8. Five random integers between 1 and 10 inclusive
  9. All multiples of 3 up to 99
  10. The powers of 2 up to 28 (2, 4, 8, … 128, 256)

Nesting Loops

Use nested for loops to print out the following patterns

*
**
***
****
*****
******
*******
********
*********
*****
****
***
**
*
**
****
******
********
  1. 6!, pronounced 6 factorial, means 6x5x4x3x2x1. Write a program to print out the first 10 factorial numbers.
  2. Print out the times tables for 1 to 10. Print them out in the format “2 x 3 = 6”
  3. Print out a chess board grid using 1s and 0s e.g. 0 1 0 1 0 1 0 1, then 1 0 1 0 1 etc to make an 8×8 grid.

Extension

Print out the following patterns, either using nested for loops or some other way…

     *
    **
   ***
  ****
 *****
******
   *
  ***
 *****
*******
   *
  ***
 *****
*******
 *****
  ***
   *

Leave a Comment