C Program for Difference between sums of odd and even digits?


Suppose we have one long integer. We have to find if the differences between the sum of the odd position digits, and the sum of the even position digits are 0 or not. The positions are start from 0 (left most).

For example, suppose a number is 156486. The odd position sum is (5 + 4 + 6) = 15, and even position sum is (1 + 6 + 8) = 15, so they are same.

To solve this problem, we can use two different ways. The first way is traversing form start to end and get the sum by alternating the position, then get the difference. The next method is simpler, and efficient. If the number is divisible by 11, then the difference must be 0. So in other words we can say that if the sum of odd position numbers and sum of even position numbers are same, then the number is divisible by 11.

Algorithm

isDiffZero(n)

begin
   if n is divisible by 11, then
      return 1
   else
      return 0
   end if
end

Example

 Live Demo

#include<stdio.h>
long isDiffZero(int n) {
   if(n % 11 == 0){
      return 1;
   } else {
      return 0;
   }
}
main() {
   int n;
   printf("Enter a number: ");
   scanf("%d", &n);
   if(isDiffZero(n)) {
      printf("Difference is zero");
   } else {
      printf("Difference is non zero");
   }
}

Output

Enter a number: 156486
Difference is zero

Updated on: 30-Jul-2019

443 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements