The Java program should sum the odd integers from 1 to the integer that the user enters. For example, if the user enters 30, the program should sum the odd integers from 1 to 30.
Print "Please enter a positive nonzero integer."
Declare a Scanner and obtain an integer from the user.
Use a Do...while statement and calculate the sum
Display the sum
Print the sum following by this message: "Total: "
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a positive nonzero integer: ");
int n = sc.nextInt();
int now = 1, total = 0;
do{
total += now;
now += 2;
}while(now < n);
System.out.println("Total: " + total);
}
}
Please up vote
Get Answers For Free
Most questions answered within 1 hours.