Algorithm for Sum of Digits of a Number in C

Kailash Chandra Behera | Saturday, November 21, 2020

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).

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

  1. Start

  2. Declare the num, rem, sum, and x four integer variables.

  3. Initialize variable sum as zero (sum=0).

  4. Ask on the screen to enter an integer value and assign it to variable x.

  5. Check the x variable value, whether it is zero or not.

  6. If the x variable value is zero then return x.

  7. If the x variable value is not zero, then asinine x variable value to variable num (num=x).

  8. 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

  9. Print the sum variable value on the screen.

  10. 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


No comments: