Computer Science, asked by kanakchamola, 1 year ago

write a program in java to calculate the sum of all odd numbers and even numbers between a range of numbers from m to n both inclusive,where m is smaller than n. Input m and n....

Answers

Answered by Anonymous
15
1. User must first enter the number upto which he/she wants to find the sum and is stored in the variable num.
2. Using for loop take the elements one by one from 1 to num.
3. Use if,else statement for each element to find whether it is odd or even by dividing the element by 2.
4. Initialize the variables odd_sum and even_sum to zero.
5. If the element is even,then increment the variable even_sum with the current element.
6. If the element is odd,then increment the variable odd_sum with the current element.
7. Print the variables odd_sum and even_sum separately and exit.
Answered by Anonymous
85

CODE


import java.util.*;

class sum

{

public void main()

{

Scanner sc=new Scanner(System.in);

System.out.println("Enter a large number");

int m=sc.nextInt();

System.out.println("Enter a small number");

int n=sc.nextInt();

int s1=0;

int s2=0;

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

{

if(i%2==0)

{

s1=s1+i;

}

else

{

s2=s2+i;

}

}

System.out.println("The sum of even numbers = "+s1);

System.out.println("The sum of odd numbers = "+s2);

}

}


NOTE

⇒ The input of m and n is taken.

⇒ The i-loop is run and if the value of 'i' is odd the value of s2 is added with the value of'i' .

⇒ The i-loop is run and if the value of 'i' is even the value of s1 is added with the value of'i' .

⇒ This logic will do well I guess :-)

Similar questions