WRITE A PROGRAM to Input a number and print the sum of the even digits and product of odd digits according to users choice in java.
Answers
Answer:
import java util.Scanner;
public class abc
{
public static void main(String args[ ])
{
Scanner scan=new Scanner(System.in)
System.out println( "1) Sum of even");
System.out println( "2) Product of odd");
System.out println(" Enter choice ");
int ch= scan.nextInt();
System.out println( "Enter number");
int num=scan.nextInt()
int sum=0;
int p=1;
int d,d1;
switch(ch)
{
case 1: for(; n!=0;n/=10)
{
d= n%10;
if (d%2==0)
sum+=d;
}
System.out.println(sum);
break;
case 2: for(; n!=0;n/=10)
{
d1= n%10;
if (d%2!=0)
p*=d;
}
System.out.println(p);
break;
default: System.out.println("Wrong choice entered");
}
}
}
Explanation:
- Using scanner class for input
- Creating class
- Since we are using switch case, inputting the choice of the user and the number
- declaring the sum and product variables with 0 and 1 respectively to avoid an error
- extracting digits
- if the extrated digit is even/odd in the cases it is added or multiplied respectively with the no. pre existing in the variable
- then it is printed
- break keyword is used to avoid fall through through the cases (to allow one specific chosen case to be executed)
- Deafult is not necessary to use but it is considered a good way to make a default case if by mistake the user has entered the wrong value/choice