
In Java as you can use a for loop when looping is required in the program. As you can see in the program below the for loop executes the commands inside et brackets until something is fulfilled:
|
All this program does is that counts from 1 to 1024 and prints
them out. It starts by making i=1. Then it sees
if i is less than or equal to 1024 and because
it isn't it, it does what is written inside the brackets. Then it
makes i bigger by one because we specified it to
be increased by one. The for loop starts again but this time it
ignores the statement that tells it to make i=1
and goes through the rest of the loop. The loop happens over and
over until the value of i <=1024. When the
loop is finished, the program prints "This program just counted 1024 times
for no reason."
Usually when loops are written, people use + + or - - rather than n = n + 1 or n = n - 1. You can see what is written below.
|
The ++ after a variable is the same thing as i=i+1 or i+=1. Any of these ways can be used in a for loop. you can also subtract the same way. N = N - 1 can also be written as N - - or N - =1.