Computer Science, asked by free2mekaushik, 17 days ago

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

Answered by Equestriadash
14

The following co‎des have been written using Python.

\tt n\ =\ int(in put("Enter\ a\ number:\ "))\\so\ =\ 0\\se\ =\ 0\\for\ i\ in\ range(1,\ n\ +\ 1):\\{\ \ \ \ \ }if\ i\%2\ !=\ 0:\\{\ \ \ \ \ }{\ \ \ \ \ }so\ =\ so\ +\ i\\{\ \ \ \ \ }else:\\{\ \ \ \ \ }{\ \ \ \ \ }se\ =\ se\ +\ i\\print("The\ sum\ of\ the\ first",\ n, "natural\ numbers\ [odd]:\ ",\ so)\\print("The\ sum\ of\ the\ first",\ n,\ "natural\ numbers\ [even]:\ ",\ se)

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 \tt for 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 \tt range() 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.

Answered by CopyThat
2

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);

}

}

Similar questions