Write a program to calculate and print the sum of odd numbers and the sum of even numbers for the first natural numbers.
The integer n is to be entered by the user.
Answers
Answered by
3
main ( )
{
int x;
printf ("enter x value");
scanf (" %d",&x);
if (x%2==0)
printf ("the number is even");
else
printf ("the number is odd");
}
{
int x;
printf ("enter x value");
scanf (" %d",&x);
if (x%2==0)
printf ("the number is even");
else
printf ("the number is odd");
}
Answered by
15
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