Sunday, March 11, 2018

Sum of even & odd

Sum of even & odd

Write a program to input an integer N and print the sum of all its even digits and sum of all its odd digits separately.

Digits means numbers not the places. That is, if the given integer is "13245", even digits are 2 & 4 and odd digits are 1, 3 & 5.
Input format :
 Integer N
Output format :
Sum_of_Even_Digits Sum_of_Odd_Digits
(Print first even sum and then odd sum separated by space)
Sample Input :
1234
Sample Output :

6 4
  1. import java.util.Scanner;
  2. public class Main 
  3. {
  4. public static void main(String[] args) 
  5. {
  6. // Write your code here
  7. int rem,odd=0,even=0,digit,input;
  8. Scanner s = new Scanner (System.in);
  9. int num = s.nextInt();
  10. while(num>0)
  11. {
  12.              digit = num % 10;
  13.              
  14.              num = num / 10;
  15.              
  16.              rem = digit % 2;
  17.              
  18.              if(rem != 0)
  19.              
  20.              odd=odd+digit;
  21.              
  22.              else
  23.              
  24.              even=even+digit;
  25.          }
  26. System.out.print(even);
  27. System.out.println(" "+odd);

  28. }
  29. }

3 comments:

  1. can you please tell the same code in python.

    ReplyDelete
    Replies
    1. evensum=0
      oddsum=0
      n = int(input())
      while(n>0):
      #b=n%10
      #n=n//10
      if b%2==0:
      evensum=evensum+b
      else:
      oddsum=oddsum+b
      print(evensum,oddsum)

      Delete
  2. digit = num % 10;

    num = num / 10;
    Can you please explain it

    ReplyDelete