Today I will teach you about For loops. A for loop has three components, an initialization, a condition, and an increment. The initialization will define a new variable with a scope of the for loop, and the condition statement will contain a boolean value that will cause the for loop to run again if the condition is true at the end of the loop. The increment will modify the value of the initialization variable each time the loop runs. Here is how you would code a for statement in java:
for(type var; condition; increment){
}
Now that you know how make for statements, I will show you an example for how to use them:
int total = 0;
Scanner scan = new Scanner(System.in);
System.out.println("how many numbers?");
int times = scan.nextInt();
for(int timesDone = 0; timesDone<=times; timesDone++){
System.out.println("number?");
int number = scan.nextInt();
total+=number;
}
System.out.print("the total is " + total);
This code will first ask you how many numbers you want to add up and then it will prompt you for those numbers one at a time. It then prints the total of those numbers added together.
Hopefully you have learned a thing or two about for loops in java, and if you have any questions, feel free to post them in the comments. I would also like to know if anyone has any suggestions for how to make these posts better.
No comments:
Post a Comment