Write a complete program that does the following: accepts a positive integer fro
ID: 3912584 • Letter: W
Question
Write a complete program that does the following:
accepts a positive integer from a user
if the integer is negative, the program should print "The number entered was negative."
if the integer is 0, the program should print "The number entered was zero."
if the integer is positive, the program should
use a loop to calculate the sum of all the odd integers from zero to the integer the user entered and
print "The sum from 0 to " followed by the integer entered, followed by " is " and followed by the calculated sum. The following could be possible outputs from your program:
The sum from all the odd integers from 0 to 5 is 9
or
The sum from all the odd integers from 0 to 8 is 16
Explanation / Answer
import java.util.Scanner;
public class Oddsum {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
//taking input from the user
System.out.print("Enter a Integer :");
int n=sc.nextInt();
//if it less than zero
if(n<0) System.out.println("The number entered was negative.");
//if it is equal to zero
else if(n==0) System.out.println("The number entered was zero.");
//if it is positive number
else{
//calculating oddsum
int oddSum=0;
for(int i=0;i<=n;i++){
if(i%2!=0) oddSum+=i;
}
System.out.println("The sum from all the odd integers from 0 to "+n+" is "+oddSum);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.