1. Using a for
loop to count the number of entered lines
Let's write a program that reads 10
lines from the keyboard and displays the number of lines that were numbers. Example:
Code  Explanation 


Create a

If the line contains multiple tokens separated by spaces, and the first of them is a number, then the hasNextInt()
method will return true
, even if the other tokens are not numbers. That means that our program will work correctly only if just one token is entered on each line.
2. Calculating the factorial using a for
loop
Let's write a program that doesn't read in anything, but instead calculates something. Something difficult. For example, the factorial of the number 10
.
The factorial of a number n
(denoted by n!
) is the product of a series of numbers: 1*2*3*4*5*..*n
;
Code  Explanation 


We store the product of numbers in the 
The starting value is f = 1
, because we are multiplying f
by the numbers. If f
were originally 0
, then the product of all the numbers multiplied by 0
would be 0
.
3. Using a for
loop to draw on the screen
Let's write a program that draws a triangle on the screen. The first line consists of 10
asterisks, the second — 9
asterisks, then 8
, etc.
Code  Explanation 


Loop through the lines (there should be

We need to have two nested loops here: the inner loop is responsible for displaying the correct number of asterisks on a given line.
And the outer loop is needed to loop through the lines.
GO TO FULL VERSION