Algorithm for Sum of Digits of a Number in C

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

  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

Kailash Chandra Behera

An IT professional with over 13 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies. Demonstrated expertise in delivering all phases of project development—from initiation to closure—while aligning with business objectives to drive process improvements, competitive advantage, and measurable bottom-line gains. Proven ability to work independently and manage multiple projects successfully. Committed to the efficient and effective development of projects in fast-paced, deadline-driven environments. Skills: Proficient in designing and developing applications using various Microsoft technologies. Total IT Experience: 13+ years

2 Comments

Previous Post Next Post

نموذج الاتصال