University of Toronto - Fall 2000
Department of Computer Science
Week 7 - Loop example
Loop to add 5 + 4 + 3 + 2 + 1
While Loop
/**
* AddFive: This program adds up all numbers, from 5 to 1.
*/
public class AddFive {
public static void main (String[] args) {
int number = 5; // 1st num to be accumulated
int sum = 0; // We've added no numbers yet
// As long as the number is bigger than 0,
// add the number to the sum, and decrease
// the number by one.
while (number > 0) {
sum += number;
number--;
}
// Display the sum
System.out.println("The sum is: " + sum);
}
}
For Loop
/**
* AddFive: This program adds up all numbers, from 5 to 1.
*/
public class AddFive {
public static void main (String[] args) {
int sum = 0; // We've added no numbers yet
// As long as the number is bigger than 0,
// add the number to the sum, and decrease
// the number by one.
for (int number=5; number > 0; number--) {
sum += number;
}
// Display the sum
System.out.println("The sum is: " + sum);
}
}