Custom Search

Friday, May 20, 2011

The for Loop

In this post we will be covering the for loop. The for loop is a block of code that can repeat itself for a set amount of repeats.  A for loop is useful when you know exactly how many times you need to loop through(v.s. a while loop).  Well, lets begin!

public class main{
public static void main(String[] args){
for(int i = 0;i<20;i++;){

System.out.println(i + "  Hello World");
}
}
}
so in this code we are declaring a class, declaring our main method and building a for loop.  
We tell the computer we want to use int(a number) i for our variable, loop for as long as i<20, and after done with each loop add 1 to i (or we would loop forever).

If you ran this code though, you would see

0 Hello World 
1 Hello World  
2 Hello World  
3 Hello World  
4 Hello World  
5 Hello World  
6 Hello World  
7 Hello World  
8 Hello World  
9 Hello World  
10 Hello World  
11 Hello World  
12 Hello World  
13 Hello World  
14 Hello World  
15 Hello World  
16 Hello World  
17 Hello World  
18 Hello World  
19 Hello World 

 You may be wondering, "Why does it only loop to 19 when we told to go to 20?" it does this because in java
the computer counts zero as its first number.  If you have any questions or ideas for future posts feel free to leave a comment below.

That wraps it up for for loops! See you in the next post.

No comments:

Post a Comment