Open In App

C Program for Difference between sums of odd and even digits

Improve
Improve
Like Article
Like
Save
Share
Report

Write a C program for a given long integer, the task is to find if the difference between sum of odd digits and sum of even digits is 0 or not. The indexes start from zero (0 index is for leftmost digit).

Examples:

Input : 1212112
Output : Yes
Explanation:
the odd position element is 2+2+1=5
the even position element is 1+1+1+2=5
the difference is 5-5=0 equal to zero.
so print yes.

Input :12345
Output : No
Explanation:
the odd position element is 1+3+5=9
the even position element is 2+4=6
the difference is 9-6=3 not equal to zero.
So print No.

Approach:

One by one traverse digits and find the two sums. If difference between two sums is 0, print yes, else no.

Below is the implementation of the above approach:

C




// C code for the above approach
#include <stdbool.h>
#include <stdio.h>
 
// Function to check if the sum of alternating digits in 'n'
// is 0
bool isDiff0(int n)
{
    // Variable to store the sum of alternating digits
    int first = 0;
    // Variable to store the sum of the other alternating
    // digits
    int second = 0;
    // A flag to alternate between 'first' and 'second' sums
    bool flag = true;
 
    while (n > 0) {
        // Extract the last digit from 'n'
        int digit = n % 10;
        if (flag) {
            // Add 'digit' to 'first' if 'flag' is true
            first += digit;
        }
        else {
            // Add 'digit' to 'second' if 'flag' is false
            second += digit;
        }
        // Toggle the flag for the next digit
        flag = !flag;
        // Remove the last digit from 'n'
        n = n / 10;
    }
 
    if (first - second == 0) {
        // Return true if the difference between 'first' and
        // 'second' sums is 0
        return true;
    }
    // Otherwise, return false
    return false;
}
 
// Drivers Code
int main()
{
    // The input number
    int n = 1243;
    if (isDiff0(n)) {
        // If isDiff0 returns true, print "Yes"
        printf("Yes\n");
    }
    else {
        // If isDiff0 returns false, print "No"
        printf("No\n");
    }
    return 0;
}


Output

Yes

Time Complexity: O(log n)
Auxiliary Space: O(1)

Please refer complete article on Difference between sums of odd and even digits for more details!



Last Updated : 20 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads