### Introduction

Here in this article, we will discuss the step-by-step process with a code example of how to write an algorithm to find the sum of digits of a number(positive number).

## Algorithm for Sum of Digits of a Number in C

### Getting Started

The follwoing given staps and code example will help you how to calculate the sum of given positive number. go throurgh the each steps which will help you to understand the code.

## Algorithm steps to find the Sum of Digits

- Start
- Declare the num, rem, sum, and x four integer variables.
- Initialize variable sum as zero (sum=0).
- Ask on the screen to enter an integer value and assign it to variable x.
- Check the x variable value, whether it is zero or not.
- If the x variable value is zero then return x.
- If the x variable value is not zero, then asinine x variable value to variable num (num=x).
- Write the process to calculate the sum of digits using the below codes.
`while(num>0) { rem=num%10; num=num/10; sum=sum+rem;`

the above code gets the rightmost digit of the number with help of remainder ‘%’ operator by dividing it with 10 and add it to sum. then divides the number by 10 with help of ‘/’ operator

- Print the sum variable value on the screen.
- Exit.

## Program:-

```
# include <stdio.h>
# include <conio.h>
int main()
{
int num, rem,sum,x;
sum=0;
x=120;
if(x!=0){
num=x;
while(num>0) {
rem=num%10;
num=num/10;
sum=sum+rem;
}
}
else
sum=x;
printf("\n sum of digits of %d=%d", x,sum);
return 0;
}
```

### Summary

With the help of the above algorithm steps and programm code, we learn how to write algorithm to find the sum of digits of a given positive number. I hope you have enjoyed it a lot.

**Thanks**

helpful content

ReplyDeletenice

ReplyDelete