Class Notes for For Loops |
|
// FOR LOOPS are also known as count controlled loops.
// For loops will repeat whatever code is inside them
// only a specific amount of times.
// Anatomy of a for loop
// for( start; stopWhenFalse; step){}
// start only runs once; start of the loop
// stopWhenFalse runs at the top of the loop
// step runs at the end of the loop
for(int i=0; i<20; i=i+5){
System.out.print(i+" ");
}
// Print "HeLlO wOrLd" 10 times
for(int i=0; i<10; i=i+1){
System.out.println("HeLlO wOrLd");
}
// Print out the numbers from 1 to 10
for(int i=1; i<=10; i=i+1){
System.out.println(i);
}
// Print out the numbers from 10 to -10
for(int i=10; i>=-10; i=i-1){
System.out.println(i);
}
// Print out the only every ten numbers from 10 to 100
for(int i=10; i<=100; i=i+10){
System.out.println(i);
}
// Add numbers 1-100
int sum = 0;
for(int i=1; i<=100; i++){
sum += i;
}
System.out.println(sum);
Videos |
|