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:
- Numbers from 1 to 70 inclusive
- Numbers from 10 to -10 inclusive
- Odd numbers from 1 to 19 inclusive
- Even numbers from 10 to -20 inclusive
- The sequence 0.3, 0.4, 0.5, 0.6, 0.7
- The sequence 0.1, 0, -0.1, -0.2, -0.3
- The square numbers 1, 4, 9, 16, … 81, 100
- Five random integers between 1 and 10 inclusive
- All multiples of 3 up to 99
- The powers of 2 up to 28 (2, 4, 8, … 128, 256)
Nesting Loops
Use nested for loops to print out the following patterns
*
**
***
****
*****
******
*******
********
*********
*****
****
***
**
*
**
****
******
********
- 6!, pronounced 6 factorial, means 6x5x4x3x2x1. Write a program to print out the first 10 factorial numbers.
- Print out the times tables for 1 to 10. Print them out in the format “2 x 3 = 6”
- 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…
*
**
***
****
*****
******
*
***
*****
*******
*
***
*****
*******
*****
***
*