w3resource

C Programming: Count Integers with Odd digit sum


38. Count Numbers with Odd Digit Sum Variants

Accept a positive integer (n) from the user. Write a C program that counts the number of positive integers from 1 to n whose digit sums are odd.

Example:
Input: n = 5
Integers less than or equal to 5 whose digit sums are odd are 1,3 and 5.
Output: 3
Input: n = 10
Integers less than or equal to 5 whose digit sums are odd are 1, 3, 5, 7, 9 and 10 (1+0 =1)
Output: 6

Test Data:
(5) -> 3
(10) -> 6
(11) -> 6

Sample Solution:

C Code:

#include <stdio.h>

// Function to calculate the sum of digits of an integer 'n'
int digit_sum(int n) {
  int d_sum = 0;
  while (n > 0) {
    d_sum += n % 10; // Extracts the last digit of 'n' and adds it to d_sum
    n /= 10; // Removes the last digit by integer division
  }
  return d_sum; // Returns the sum of digits
}

// Function to count the number of integers with odd digit sum from 1 to 'num'
int test(int num) {
  int result = 0;
  for (int i = 1; i <= num; i++) {
    if (digit_sum(i) % 2 != 0) { // Checks if the digit sum of 'i' is odd
      result++; // Increments the counter if the digit sum is odd
    }
  }
  return result; // Returns the count of integers with odd digit sum
}

// Main function
int main(void) {
  int n = 5;
  printf("\nIntegers with Odd digit sum from 1 and %d = %d", n, test(n)); // Displaying the count of integers with odd digit sum up to 'n'

  n = 10;
  printf("\nIntegers with Odd digit sum from 1 and %d = %d", n, test(n)); // Displaying the count of integers with odd digit sum up to 'n'
}

Sample Output:

Integers with Odd digit sum from 1 and 5 = 3
Integers with Odd digit sum from 1 and 10 = 6

Flowchart:

Flowchart: Count Integers with Odd digit sum

For more Practice: Solve these Related Problems:

  • Write a C program to count the numbers from 1 to n whose digit sum is odd by iterating through each number.
  • Write a C program to compute the digit sum for each number and use a function to check oddness, tallying the results.
  • Write a C program to optimize the odd digit sum count by precomputing digit sums for ranges of numbers.
  • Write a C program to recursively calculate digit sums and count how many numbers up to n have an odd total.

Go to:


PREV : Count Unique Digit Numbers Variants.
NEXT : C programming: Functiion Exercises - Home page.

C Programming Code Editor:



Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.