# C Programming: Count Integers with Odd digit sum

## C Programming Mathematics: Exercise-38 with Solution

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>
int digit_sum(int n) {
int d_sum = 0;
while (n > 0) {
d_sum += n % 10;
n /= 10;
}
return d_sum;
}
int test(int num) {
int result = 0;
for (int i = 1; i <= num; i++) {
if (digit_sum(i) % 2 != 0) {
result++;
}
}
return result;
}
int main(void) {
int n = 5;
printf("\nIntegers with Odd digit sum from 1 and %d = %d", n, test(n));
n = 10;
printf("\nIntegers with Odd digit sum from 1 and %d = %d", n, test(n));
}
```

Sample Output:

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

**Flowchart: **

**C Programming Code Editor:**

**Improve this sample solution and post your code through Disqus.**

**Previous:** Count unique digits of integers.

**Next:** C programming: Functiion Exercises - Home page.

**What is the difficulty level of this exercise?**

Test your Programming skills with w3resource's quiz.

## C Programming: Tips of the Day

**What's the point of const pointers?**

const is a tool which you should use in pursuit of a very important C++ concept:

Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.

Even though it does not change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do. Imagine the following typo:

void foo(int* ptr) { ptr = 0;// oops, I meant *ptr = 0 }

If you use int* const, this would generate a compiler error because you're changing the value to ptr. Adding restrictions via syntax is a good thing in general. Just don't take it too far -- the example you gave is a case where most people don't bother using const.

Ref : https://bit.ly/33Cdn3Q

**Weekly Trends**- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises