22.1k views
0 votes
Write a java program that asks the user to type a positive number n and prints the series using do while loop: 1+4+9+16…+(n2). Example: If the input is 4 , then the program will display 1+4+9+16.

User Ilena
by
7.5k points

1 Answer

5 votes

Final answer:

To write a Java program that prints the series using a do while loop, follow these steps: ask the user for a positive number n, use a do while loop to calculate the square of each number from 1 to n, and accumulate the sum of the squared numbers. Finally, print the series and the sum of the numbers.

Step-by-step explanation:

To write a Java program that prints the series using a do while loop, you can start by asking the user to input a positive number n. Then, you can use a do while loop to iterate through the numbers from 1 to n and calculate the square of each number.

Inside the loop, you can accumulate the sum by adding each squared number to a running total. Finally, you can print the series using the accumulated sum.

Here's an example implementation:

import java.util.Scanner;

public class SeriesProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive number: ");
int n = scanner.nextInt();
int sum = 0;
int i = 1;
do {
int square = i * i;
sum += square;
if (i != 1) {
System.out.print("+ ");
}
System.out.print(square);
i++;
} while (i <= n);
System.out.println(" = " + sum);
scanner.close();
}
}

User Boris Stitnicky
by
8.1k points