# C Program to Find Sum of Odd Digits in a Given Number

## Introduction

In this post, I am going to write a c program to find the sum of odd digits in a given number. After explaining this program, I will rewrite the c program to find the sum of even digits in a given number. We will have to make only one change that I will explain in the respective section.

We will perform the following steps for writing this program.

1. Read a number from the user.
2. Check each and every digit in the number.
3. If the digit is odd then add this number and stored it in another variable i.e. sum.
4. If the digit is not odd then check the next digits in the same number and repeat step 3 if necessary.
5. Print the result.

The above steps are so simple. Now, we will see the expected output for the c program to find the sum of odd digits in a given number.

### Expected Output

I hope, you have got the idea about the title of the program. Now, let us see the actual c program.

## C Program to Find Sum of Odd Digits in a Given Number

```#include <stdio.h>
#include <stdlib.h>
int main()
{
int num,sum=0,rem,n;
printf("Enter a number\n");
scanf("%d",&num);
n=num;
while(num>0)
{
rem=num%10;
if(rem%2==1)
{
sum=sum+rem;
}
num=num/10;
}
printf("Sum of odd digits of %d is %d",n,sum);
return 0;
}```

In the above program, I have declared four integer variables i.e. num, sum, rem and n.

We will read a number from the user and that number will be stored in the variable num.

The value of num is copied to the variable n. Because in the while loop, the value of the variable num will become zero. Therefore, I have made an extra copy of that variable num.

We have to find the sum of odd digits in a number. For this, we will have to separate each and every digit. By using the modulo operator, we are separating digits and storing that separated digit in the variable rem. Here, rem means remainder after division.

The variable sum will store the sum of all the odd digits. We are performing this operation in the while loop after verifying whether the separated digit is odd or not.

At the last, we will display the result or output using the printf statement.

By making some little bit changes, you can also write the c program to find the sum of even digits in a number. Logic will remain the same. We will make some changes in if statement. See the following program.

## Sum of Even Digits in a Number in C

```#include <stdio.h>
#include <stdlib.h>
int main()
{
int num,sum=0,rem,n;
printf("Enter a number\n");
scanf("%d",&num);
n=num;
while(num>0)
{
rem=num%10;
if(rem%2==0)
{
sum=sum+rem;
}
num=num/10;
}
printf("Sum of odd digits of %d is %d",n,sum);
return 0;
}
```

If you have carefully observed, then I have rewritten the statement “if(rem % 2 == 0)”. This statement will decide whether a digit is even or not.

I hope you have understood this program. If you have any difficulty then you can contact me.

Thank you.