215k views
1 vote
Write a java program that asks the user to type a positive number n and prints the sum of odd numbers using while loop: 1+3+5+7…+(2n−1). Example: If the input is 4 , then the program will print 16 .

1 Answer

6 votes

Final answer:

To write a Java program that calculates the sum of odd numbers up to a given positive number n, we can use a while loop. The question asks for a Java program to calculate the sum of odd numbers up to (2n−1), which equates to the square of n. A simple Java program using a while loop can solve this by continuously adding odd numbers and updating the sum until the specified condition is met.

Step-by-step explanation:

To write a Java program that calculates the sum of odd numbers up to a given positive number n, we can use a while loop. Here's how the program can be implemented:

import java .util .Scanner;

public class Sum Of Odds {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter a positive number: ");
int n = input.nextInt();

int sum = 0;
int i = 1;

while (i <= 2 * n - 1) {
sum += i;
i += 2;
}

System.out.println("The sum of odd numbers up to " + n + " is: " + sum);
}
}

The program asks the user to input a positive number n using the Scanner class. The while loop then calculates the sum of odd numbers starting from 1 up to (2n - 1) and stores it in the variable sum. Finally, the program prints the calculated sum.

The question asks for a Java program to calculate the sum of odd numbers up to (2n−1), which equates to the square of n. A simple Java program using a while loop can solve this by continuously adding odd numbers and updating the sum until the specified condition is met.

The subject of the question is to write a Java program that calculates the sum of odd numbers up to (2n−1) using a while loop, where n is a positive number provided by the user. The mathematical expression for the summation of odd numbers up to the nth term is n². This can be visualized by pairing each odd number from the start with an odd number from the end of the series, noting that the sum of each pair is 2n and since there are n such pairs, the total sum is n×(2n)=2n².

Here is a simple Java program that performs this computation:

import java.util.Scanner;

class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please type a positive number n: ");
int n = scanner.nextInt();
int sum = 0;
int i = 1;

while (i <= 2 * n - 1) {
sum += i;
i += 2;
}

System.out.println("The sum of odd numbers is: " + sum);
}
}
User Klimbo
by
9.1k points