Computer Applications
Write a program to calculate the sum of all odd numbers and even numbers between a range of numbers from m to n (both inclusive) where m < n. Input m and n (where m < n).
Java
Java Iterative Stmts
87 Likes
Answer
import java.util.Scanner;
public class KboatOddEvenSum
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter m: ");
int m = in.nextInt();
System.out.print("Enter n: ");
int n = in.nextInt();
long sumOdd = 0, sumEven = 0;
if (m > n) {
System.out.println("m should be less than n");
}
else {
for (int i = m; i <=n; i++) {
if (i % 2 == 0)
sumEven += i;
else
sumOdd += i;
}
System.out.println("Even Sum: " + sumEven);
System.out.println("Odd Sum: " + sumOdd);
}
}
}
Variable Description Table
Program Explanation
Output
Answered By
39 Likes
Related Questions
Write the program in Java to display the first ten terms of the following series:
2, 5, 10, 17,
Write a program to display all the numbers between m and n input from the keyboard (where m<n, m>0, n>0), check and print the numbers that are perfect square. e.g. 25, 36, 49, are said to be perfect square numbers.
Write a program to input any 50 numbers (including positive and negative). Perform the following tasks:
(a) Count the positive numbers
(b) Count the negative numbers
(c) Sum of positive numbers
(d) Sum of negative numbers
Write a program to enter any 50 numbers and check whether they are divisible by 5 or not. If divisible then perform the following tasks:
(a) Display all the numbers ending with the digit 5.
(b) Count those numbers ending with 0 (zero).