How to find sum of digits in C++

In this tutorial, we will learn how to find sum of all digits of a number in c++ with some easy examples. Sum of digit means add all the digits of the number, for example, a number is 873.its sum of all digit is 8+7+3=18. So by using given code we can easily write the program.

Find sum of all digits of a number in C++

let’s learn this with easy steps.

  • Firstly we start from header file in which we used two header file(iostream,conio) iostream is used for input output stream and conio provides console input/output.
#include<iostream.h>
#include<conio.h>
  • then this is main function.Int tells the compiler that function will return an integer number.
int main()
  • then give variables with Int.a=0,b=0,c=0 means it not take the garbage value in the output.
int a,b,c;
a=0;
b=0;
c=0;
  • for enter or input the number and that number will store in a where b=a means original data should not change.
cout<<"enter number:";
cin>>a;
b=a;

output :

Enter number:

  • Now while condition starts and goes on till it becomes (b=0) then it comes out of loop.
while(b!=0)

  • New variable d used for storing the remainder and it will not use garbage value so we are using (d=0).
int d;
d=0;
  • original data of b that comes in d and add up with C because c stores the result values.
    d=b%10;
    c=c+d;
  • here after dividing the number by 10 we get all digits except last digit.
    b=b/10;
    

     

  • In first it adds 0 and last digit and store in sum variable, in second it adds previous sum and last digit of new number and again store in sum variable and it works till while condition is not false and show output in C.
  • Now combine the whole part of the program in a single window.
#include<iostream.h>
#include<conio.h>
int main()//main function
{
  int a,b,c;
  a=0;
  b=0;
  c=0;
  clrscr(); 
 cout<<"enter number:"; 
 cin>>a;
  b=a;
while(b!=0)
{
  int d;
  d=0;
  d=b%10;
  c=c+d;
  b=b/10;
}
  
cout<<"output"<<c; 
return 0; 
}

output:

Enter number:123
Sum=6

Also read:



Leave a Reply

Your email address will not be published. Required fields are marked *