Computer Science, asked by lakshmivijiaya0, 3 months ago

wap to calculate and display the sum of all the odd number and even number between a range of number m to m


anindyaadhikari13: Please mention the programing language.

Answers

Answered by anindyaadhikari13
4

Required Answer:-

Question:

  • Write a program to calculate and display the sum of all the odd numbers and even number between a given range of numbers m to n.

Solution:

Here comes the program. It is written in Java.

import java.util.*;

public class Sum {

 public static void main(String[] args) {

    Scanner sc=new Scanner(System.in);

    int m, n;

    System.out.print("Enter starting range: ");

    m=sc.nextInt();

    System.out.print("Enter ending range:   ");

    n=sc.nextInt();

    int s1=0, s2=0;

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

      if(i%2==1)

        s1+=i;

      else

        s2+=i;

    }

    System.out.println("Sum of Odd numbers in this range: "+s1);

    System.out.println("Sum of Even numbers in this range: "+s2);

    sc.close();

 }

}

Algorithm:

  • Start
  • Enter the range.
  • Loop through the given range.
  • If the number is even, add them to s2 variable else add them to s1 variable.
  • Display sum of odd and even numbers in the range.
  • Stop

Sample I/O:

Enter starting range: 1

Enter ending range:   10

Sum of Odd numbers in this range: 25

Sum of Even numbers in this range: 30

Attachments:
Answered by Oreki
1

Program:

import java.util.Scanner;

public class RangeSum {

   public static void main(String[ ] args) {

       Scanner sc = new Scanner(System.in);

       System.out.println("Enter the range : ");

       System.out.print("Start - ");

       int start = sc.nextInt( );

       System.out.print("Stop - ");

       int stop = sc.nextInt( );

       int sumOdd = 0, sumEven = 0;

       for (int i = start; i <= stop; i++) {

           if (i % 2 == 0)

               sumEven += i;

           else sumOdd += i;

       }

       System.out.println("Even sum - " + sumEven);

       System.out.println("Odd sum - " + sumOdd);

   }

}

Algorithm:

  • Accepting the range.
  • Iterating over the range.
  • If a number is even in the range adding it to the even accumulator - sumEven, if odd then to odd accumulator - sumOdd.
  • Printing the final values of the accumulators.
Attachments:

Anonymous: Amazing !
Oreki: Thanks!
Similar questions