Question:
ICSE 2006 Question 4
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
Source Code:
public class ICSE2006_4
{
public static void main(int n)throws Exception
{
int sumo=0, sume=0;
for(int i=1; i<=n; i++)
if(i%2==0)
sume+=i;
else
sumo+=i;
System.out.println("The sum of odd numbers is "+sumo+".\nThe sum of even numbers is "+sume+".");
}
}
Result:
INPUT:
28
OUTPUT:
The sum of odd numbers is 196.
The sum of even numbers is 210.
No comments:
Post a Comment