Sum Digits
Complete Source
Code
/*
In this program, the user will be asked to input an integer N. The
computer will then calculate the sum of all the integers from 1 to N and
display it to the user on standard output. If N is less than 1, the
computer will simply display the number 0. */
public class SumDigits {
public static void main(String[]
args) {
// Declares all the variables
int N, S, n;
// Asks user to input an integer
System.out.println();
System.out.print("Please enter an integer: ");
N = TextIO.getlnInt();
// Initializes the variables
n = 1;
S = 0;
// Iterates the sum
while (n <= N) {
S = S + n;
n = n + 1;
}
// Displays the iterated sum on standard output
System.out.println();
System.out.println("The sum of all the integers
from 1 to " + N + " is " + S + ".");
} // end of main()
} // end of class SumDigits |