Input a number and print the sum of the even digits and product of odd digits according to users choice in java
Answers
Using scanner class :-
import java.util.*;
public class brainiliest
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of digits you want to enter");
int no= sc.nextInt();
double dig;
int i;
double sum=0;
double product=1;
for(i=1;i<=no;i++)
{
System.out.println("Enter number");
dig=sc.nextDouble();
if(dig%2==0)
{
sum=+dig;
}
else if(dig%2!=0)
{
product*=dig;
}
}
System.out.println("The sum of even digits is = "+sum);
System.out.println("The product of odd digits is = "+product);
}
}
Answer:
The following Java Program prints the sum of the even digits and product of odd digits
import java.util.*;
public class example
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the length of the digit\n");
int no= sc.nextInt();
double digit;
int i;
double sum,product=0,1;
for(i=1;i<=no;i++)
{
System.out.println("Enter the digits of the number");
digit=sc.nextDouble();
if(digit%2==0)
{
sum=sum+digit;
}
else if(digit%2!=0){
product = product*digit;
}
}
System.out.println("\n Sum of even digits is = "+sum);
System.out.println("\N Product of odd digits is = "+product);
}
}
Explanation:
Let's understand the code above:
- First, we ask the user to enter the length of the digit and then we take the input of the number.
- Since our task is to print the sum of even digits like(2,4,6....) and the product of odd digits like(3,5,9....) so create two variable sums and products respectively to store the output.
- Then we start iterating over the digits of the numbers and check whether the digit is divisible by 2 or not.
- If it is divisible by 2 that means it is even so we add it to the sum variable.
- If it is not divisible by 2 that means it is odd so we multiply it with the product variable.
- Loop continues till the end of the number.
- Lastly, we print the output.
#SPJ2