Computer Science, asked by electricbeef1, 3 months ago

Write a program to display the sum of positive even numbers and negative odd numbers entered by the user.
(in java code)

Answers

Answered by Anonymous
2

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 ❤️

Answered by anindyaadhikari13
4

Required Answer:-

Question:

  • Write a Java program to display the sum of positive even numbers and negative odd numbers.

Solution:

Here is the code.

  1. import java.util.*;
  2. public class Sum {
  3. public static void main(String[] args) {
  4. Scanner sc=new Scanner(System.in);
  5. System.out.print("How many numbers? ");
  6. int n=sc.nextInt();
  7. System.out.println("Enter the numbers: ");
  8. int a=0, b=0;
  9. for(int i=1;i<=n;i++)
  10. {
  11. System.out.print("Enter: ");
  12. int x=sc.nextInt();
  13. if(x%2==0 && x>0)
  14. a+=x;
  15. if(x%2==-1 && x<0)
  16. b+=x;
  17. }
  18. System.out.println("Sum of positive even numbers: "+a);
  19. System.out.println("Sum of negative odd numbers: "+b);
  20. sc.close();
  21. }
  22. }

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.

Attachments:
Similar questions
Math, 1 month ago