A very important concept in programming is looping. In this post we will take a look at the for loop in java. Let us say for example that we want to display some text 20 times. If we were to code that without a loop, we would have to write 20 statements, very tedious indeed. Here is how a for loop in java will help us out:
public class ForLoopExample {
public static void main(String[] args){
for (int index = 1; index <= 20; index++){
System.out.println("I am so glad I didn't have to type this " + index + " times!");
}
}
}
If you look at the actual for statement, you will notice a couple of things in the brackets. First we see the statement of int index = 1; what this does is declare an int variable to store a number as a counter of sorts, so the program knows how many times it has run through the loop. The second part index <= 20; tells the program to run the code until the index variable holds a value of 20. The third part index++ instructs java to increment the variable index by one every time the loop is run through.
Below is what the result is when you run the program:
I am so glad I didn't have to type this 1 times!
I am so glad I didn't have to type this 2 times!
I am so glad I didn't have to type this 3 times!
I am so glad I didn't have to type this 4 times!
I am so glad I didn't have to type this 5 times!
I am so glad I didn't have to type this 6 times!
I am so glad I didn't have to type this 7 times!
I am so glad I didn't have to type this 8 times!
I am so glad I didn't have to type this 9 times!
I am so glad I didn't have to type this 10 times!
I am so glad I didn't have to type this 11 times!
I am so glad I didn't have to type this 12 times!
I am so glad I didn't have to type this 13 times!
I am so glad I didn't have to type this 14 times!
I am so glad I didn't have to type this 15 times!
I am so glad I didn't have to type this 16 times!
I am so glad I didn't have to type this 17 times!
I am so glad I didn't have to type this 18 times!
I am so glad I didn't have to type this 19 times!
I am so glad I didn't have to type this 20 times!
No comments:
Post a Comment