Input number and find sum of all odd and even digits in it using for loop in Java
for Loop - Question 12
In this question, we will see how to input a number and find the sum of all odd digits and even digits present in the number separately in Java programming using for loop. To know more about for loop click on the for loop lesson.
Q12) Write a program in Java to input a number and find the sum of all odd digits and even digits present in the number separately using for loop.
Program
import java.util.Scanner;
public class Q12
{
public static void main(String args[])
{
int i,n,d,even=0,odd=0;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number ");
n=sc.nextInt();
for(i=n; i>0; i=i/10)
{
d=i%10;
if(d%2==0)
{
even=even+d;
}
else
{
odd=odd+d;
}
}
System.out.println("Sum of even digits = " + even);
System.out.println("Sum of odd digits = " + odd);
}
}
Output
Enter a number 45612 Sum of even digits = 12 Sum of odd digits = 6