Q.1 Write a program to compulsory Marks : 10 calculate and print the sum of odd numbers and sum of even numbers for the first n natural numbers. The integer n is to be entered by the user.
Answers
The following codes have been written using Python.
Once the input 'n' has been entered, we assign two variables 'so' and 'se' to represent the sum of the first 'n' natural odd and even numbers. We use a loop to perform the addition. A loop is an iteration statement used to perform repeated checking over a given range. We give the range as (1, n + 1) since natural numbers start from 1 and the function always excludes the last number. Once the loop starts, conditional statements are given to test if the traversing variables are odd or even. If they're either, they get added to their respective variables and are later printed.
Answer:
JAVA:-
import java.util.*;
public class Brainly
{
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);
}
}