LOOPS&CONDITIONS: Create a program that takes in two numbers and then calculate the sum of all even numbers in between the two numbers. The program should also calculate the products of all the odd numbers between the provided numbers.
Sample run 1:
Enter two numbers: 2 8
Output:
Even numbers: 2 4 6 8
Odd numbers: 3 5 7
Sum of even numbers = 20
Product of odd numbers = 105
Source code
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("Enter two numbers: ");
int n1=in.nextInt();
int n2=in.nextInt();
int sumEven=0;
int productOdd=1;
System.out.print("Even numbers: ");
for(int i=n1;i<=n2;i++){
if (i%2==0){
System.out.print(i+" ");
sumEven+=i;
}
}
System.out.println();
System.out.print("Odd numbers: ");
for(int i=n1;i<=n2;i++){
if (i%2!=0){
System.out.print(i+" ");
productOdd*=i;
}
}
System.out.print("\nSum of even numbers = "+sumEven);
System.out.print("\nProduct of odd numbers = "+productOdd);
}
}
Output
Comments
Leave a comment