Java program The sum of squares of the first n odd natural n
Java program.
The sum of squares of the first n odd natural numbers is the following computation:
1^2 + 3^2+ 5^2+ ……………..+ (2n-1)^2 =(n(2n-1)(2n+1))/3
1. Create a package name home.work1
2. Create a class named OddNumbers under the above package with the mail method
3. Write the static method sumWithLoop, that takes the number n as its argument. The code for this method should use the formula shown on the right hand side of the above equation. The method returns the computed sum.
4. Write the static method sumWithoutLoop, that takes the number n as its argument. The code for this method should use the formula shown on the right hand side of the above equation. The method returns the computed sum.
5. The code in the main method should do the following:
a. Prompt the user for a string input value for the number.
b. Convert the string to an integer and store it in the variable named inputNumber. You can assume that the user enters a valid integer number.
c. Invoke the method, sumWithLoop, and store the result into the variable, result1.
d. Invoke the method, sumWithLoop, and store the result into the variable, result2.
e. Print the two results to the console.
f. Using an if-else statement, show that the two values are indeed the same. In the else part, show that your code is incorrect.
g. Using a message dialog, show the summary of the above values to the user. See the sample input and output below.
Please help for this Java program
Solution
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package home.work1;
import java.util.Scanner;
public class OddNumbers {
public static int sumWithLoop(int n)
{
int i = 1;
int sum = 0;
while(i<=(2*n-1))
{
sum = sum+i*i;
i = i+2;
}
return sum;
}
public static int sumWithoutLoop(int n)
{
return (n*(2*n-1)*(2*n+1))/3;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String number;
System.out.println(\"Input a number : \");
number = input.next();
int n = Integer.parseInt(number);
int res1 = sumWithLoop(n);
int res2 = sumWithoutLoop(n);
if(res1==res2)
System.out.println(\"Values are same.\");
else
System.out.println(\"Code is incorrect.\");
System.out.println(\"For value \"+n+\" sum returned by sumWithValue function is : \"+res1);
System.out.println(\"For value \"+n+\" sum returned by sumWithoutValue function is : \"+res2);
}
}
OUTPUT:
run:
Input a number :
29
Values are same.
For value 29 sum returned by sumWithValue function is : 32509
For value 29 sum returned by sumWithoutValue function is : 32509
BUILD SUCCESSFUL (total time: 3 seconds)

