Write a program to calculate and print the sum of odd numbers and the sum
of even numbers for the first n natural number. The integer n is to be entered
by the user
Answers
Answered by
0
Answer:
The sum of the even numbers will be 2 ( 1 + 2 + 3 + … + n/2) if n is even.
= 2 (n/2) (n/2 +1) / 2
= n^2 / 4 + n/2 or you prefer n/2 (n/2 + 1). (****)
Check to see if it works.
The sum of the even numbers for the first 6 natural numbers is 2+4+6 = 12
and 3 (3+1) = 12. It seems to work.
The sum of the even numbers will be 2 (1 + 2 + 3 +…+ ((n+1)/2) if n is odd.
= 2 (((n-1)/2 ) ((n-3)/2)))
= (n-1) ( n-3)/2. (****)
Check to see if it works.
The sum of the even numbers for the first 9 natural numbers is 2+4+6+8= 20
and (8)(5)/2 = 20. Again it seems to work.
The sum of the odd numbers will always be a perfect square. It will be (n/2)^2 if n is even
= n^2 / 4. (****)
Check to see if it works.
The sum of the odd numbers for the first 8 natural numbers is 1+3+5+7=16
and 8^2 / 4 = 16. It seems to work.
The sum of the odd numbers will always be a perfect square. It will be ((n + 1) / 2)^2 if n if odd.
= (n + 1)^2 / 4. (****)
Check to see if it works.
The sum of the odd numbers for the first 11 natural numbers is 1+3+5+7+9+11=36
and 12^2 / 4 = 144/4 = 36.
Answered by
0
Question:
Write a program to calculate and print the sum of odd numbers and the sum of even numbers for the first n natural numbers. The integer n is to be entered by the user.
Solution:
Language used : Java
import java.util.*;
public class OddEven
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,s1=0,s2=0;
System.out.println("Enter a number:");
n=sc.nextInt();
for(i=1;i<=n;i++)
{
if(i%2==0)
s1=s1+i;
else
s2=s2+i;
}
System.out.println("Sum of even numbers="+s1);
System.out.println("Sum of odd numbers="+s2);
}
}
Similar questions