Write a program to display the sum of positive even numbers and negative odd numbers entered by the user.
(in java code)
Answers
package com.hubberspot.java.example;
import java.util.Scanner;
public class SumArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int [] numbers = new int[0];
int number;
String nextLine;
do {
System.out.print("Enter the number : ");
number = scanner.nextInt();
nextLine = scanner.nextLine();
if(number != 0) {
numbers = add(numbers, number);
}
} while(number != 0);
int negativeSum = 0;
int oddSum = 0;
int evenSum = 0;
for(int i = 0; i < numbers.length; i++ )
{
if( numbers[i] < 0 )
{
negativeSum = negativeSum + numbers[i];
}
else if( numbers[i] % 2 == 0 )
{
evenSum = evenSum + numbers[i];
}
else
{
oddSum = oddSum + numbers[i];
}
}
System.out.println( "Sum of negative numbers : " + negativeSum );
System.out.println( "Sum of positive even numbers: " + evenSum );
System.out.println( "Sum of positive odd numbers: " + oddSum );
}
private static int[] add(int[] numbers, int number) {
Have a nice day mate ❤️
Required Answer:-
Question:
- Write a Java program to display the sum of positive even numbers and negative odd numbers.
Solution:
Here is the code.
- import java.util.*;
- public class Sum {
- public static void main(String[] args) {
- Scanner sc=new Scanner(System.in);
- System.out.print("How many numbers? ");
- int n=sc.nextInt();
- System.out.println("Enter the numbers: ");
- int a=0, b=0;
- for(int i=1;i<=n;i++)
- {
- System.out.print("Enter: ");
- int x=sc.nextInt();
- if(x%2==0 && x>0)
- a+=x;
- if(x%2==-1 && x<0)
- b+=x;
- }
- System.out.println("Sum of positive even numbers: "+a);
- System.out.println("Sum of negative odd numbers: "+b);
- sc.close();
- }
- }
Explanation:
- In this program, we are asked to find out the sum of positive even numbers and negative odd numbers. To check whether it is odd or even, we will check if the remainder obtained by dividing the number by 2 is 1 or 0. If it is 0, then it is even else it's odd. But dividing negative odd number by 2 gives -1 as remainder. In this way, we will check if the number is even positive or odd negative and we will find out the sum of both and display it.
Output is attached.