CSC108 Lecture #4 Example 1


AddFive.java

/**
 * AddFive: This program adds up all numbers, from 1 to 5.
 */
	
public class AddFive {
	public static void main (String[] args) {

		int number = 1;  // 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 increase
		// the number by one.
		while (number < 6) {
			sum += number;
			number++;
		}

		// Display the sum
		System.out.println("The sum is: " + sum);
	}
}

Output

The sum is: 15

[ CSC108 Home | Outline | Announcements | Newsgroup | Assignments | Lectures | Marks | Links ]


U of T IMAGE

© Copyright 2000. All Rights Reserved.