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

In C, we can find the difference between the sum of digits at odd positions and even positions in a number. The positions are counted from left to right starting at index 0. If this difference is zero, it indicates a special mathematical property.

For example, in the number 156486:

  • Even positions (0, 2, 4): 1 + 6 + 8 = 15
  • Odd positions (1, 3, 5): 5 + 4 + 6 = 15
  • Difference: 15 − 15 = 0

Syntax

int checkDifference(int number);
// Returns 1 if difference is zero, 0 otherwise

Method 1: Using Divisibility Rule

A number is divisible by 11 if the difference between the sum of digits at odd and even positions is zero. This provides an efficient solution −

#include <stdio.h>

int isDiffZero(int n) {
    if (n % 11 == 0) {
        return 1;
    } else {
        return 0;
    }
}

int main() {
    int n = 156486;
    printf("Number: %d<br>", n);
    
    if (isDiffZero(n)) {
        printf("Difference is zero<br>");
    } else {
        printf("Difference is non-zero<br>");
    }
    
    return 0;
}
Number: 156486
Difference is zero

Method 2: Direct Calculation

This method actually calculates the sums of digits at odd and even positions −

#include <stdio.h>

int calculateDifference(int n) {
    int oddSum = 0, evenSum = 0;
    int position = 0;
    
    while (n > 0) {
        int digit = n % 10;
        if (position % 2 == 0) {
            evenSum += digit;  /* Even position from right */
        } else {
            oddSum += digit;   /* Odd position from right */
        }
        n /= 10;
        position++;
    }
    
    printf("Even position sum: %d<br>", evenSum);
    printf("Odd position sum: %d<br>", oddSum);
    
    return evenSum - oddSum;
}

int main() {
    int n = 156486;
    printf("Number: %d<br>", n);
    
    int difference = calculateDifference(n);
    printf("Difference: %d<br>", difference);
    
    if (difference == 0) {
        printf("Difference is zero<br>");
    } else {
        printf("Difference is non-zero<br>");
    }
    
    return 0;
}
Number: 156486
Even position sum: 15
Odd position sum: 15
Difference: 0
Difference is zero

Key Points

  • Method 1 uses the mathematical property that numbers divisible by 11 have zero difference
  • Method 2 provides actual sum calculations for verification
  • Position counting starts from 0 (rightmost digit)

Conclusion

Both methods effectively determine if the difference between odd and even position digit sums is zero. The divisibility method is more efficient, while direct calculation provides detailed insight into the sums.

Updated on: 2026-03-15T11:02:38+05:30

685 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements