Prompt the user for a positive whole number (call it n)
Use a loop to calculate the following:
Sum: 1+2+...+n
Sum of squares: 1^2 + 2^2 + ... + n^2
factorial: 1 x 2 x ... x n
Print out the numbers when the loop is done.
Do this with a for loop and a while loop.
Call the class LoopArithmetic
Sample output:
The sum from 1 up to 5 is: 15
The sum of squares 1 to 5 is: 55
The factorial of 5 is: 120
Provide output for at least 3 different numbers.
import java.util.Scanner; public class LoopArithmetic { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a positive integer: "); int n = in.nextInt(); int sum = 0, sumSquares = 0, factorial = 1, j = 1; for (int i = 1; i <= n; i++) { sum += i; sumSquares += i * i; } while (j <= n) { factorial *= j; j++; } System.out.println("The sum from 1 up to " + n + " is: " + sum); System.out.println("The sum of squares 1 to " + n + " is: " + sumSquares); System.out.println("The factorial of " + n + " is: " + factorial); } }
Get Answers For Free
Most questions answered within 1 hours.