This blog is under construction

Wednesday, 10 July 2013

C program to find the sum of odd positioned digits and even positioned digits of a number separately

Write a C program to find the sum of odd positioned digits and even positioned digits of a number separately.


  #include <stdio.h>

  int main() {
        int value, digit, oddSum, evenSum, rev, count = 1;

        rev = oddSum = evenSum = 0;

        /* get the input value from the user */
        printf("Enter the input number:");
        scanf("%d", &value);

        /* 
         * Reverse the number first. Because, we will
         * reaping digits from the LSB to MSB 
         */
        while (value > 0) {
                digit = value % 10;
                rev = (rev * 10) + digit;
                value = value / 10;
        }

        value = rev;

        /*
         * extract digits from LSB to MSB and add
         * even digits to evensum and odd digits to oddSum
         */
        while (value > 0) {
                digit = value % 10;
                if (count % 2 == 0) {
                        evenSum = evenSum + digit;
                } else {
                        oddSum = oddSum + digit;
                }
                value = value / 10;
                count++;
        }

        /* print the sum of odd and even digits seperately */
        printf("Sum of odd digits is %d\n", oddSum);
        printf("Sum of even digits is %d\n", evenSum);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the input number:323232
  Sum of odd digits is 9
  Sum of even digits is 6



1 comment: