Computer Science, asked by adbhutha17, 9 months ago

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 through Scanner class.​

Answers

Answered by srajfaroquee
5

Note : I am using C++ language.

#include<iostream>  

using namespace std;

int main ( ){

   int n, sumEven= 0, sumOdd = 0;

   cout<<"Enter the value of  n:" ;

   cin>>n;

   for(int i =1 ;i <= n ;i++){

       if(i%2 == 0){

           sumEven += i  ;

       }

       else {

           sumOdd += i ;

       }

   }

   cout<<"Sum of Even natural number is " <<sumEven <<" upto " <<n <<" terms." <<endl;

   cout<<"Sum of Odd natural number is " <<sumOdd <<" upto " <<n <<" terms." <<endl;

   return 0;

}

**Please mark this ans as Brainliest answer!

Answered by duragpalsingh
1

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