Thursday, September 13, 2018

SUM OF DIGITS

  • Problem Description

    Jagan played maths game with his friend sanjay to find sum of digits of the number he said.
    Help to jagan and sanjay to solve it by your code using union.

    Input Method

    Integer ranges from 1 to 999

    Output Method

    sum of digits of the number

    Mandatory:

    1. Create union name as "Data"
    2. The variable name for union is "data"

  • CODING ARENA
  • #include <stdio.h>
    int sum(int num)
    {
      if(num!=0)
      {
        return (num%10+sum(num/10));
      }
      else
        return 0;
    }
    union Data
    {
      int num, res;
    }data;

    int main()
    {
      scanf("%d",&data.num);
      data.res=sum(data.num);
      printf("%d",data.res);
      return 0;
    }

  • Test Case 1

    Input (stdin)
    123
    
    
    Expected Output
    6
  • Test Case 2

    Input (stdin)
    345
    
    
    Expected Output
    12

No comments:

Post a Comment