# 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)
is used for input output stream and**iostream**provides console input/output.**conio**

#include<iostream.h> #include<conio.h>

- then this is main function.
tells the compiler that function will return an integer number.**Int**

int main()

- then give variables with
means it not take the garbage value in the output.*Int.a=0,b=0,c=0*

int a,b,c; a=0; b=0; c=0;

- for enter or input the number and that number will store in
where**a**means original data should not change.**b=a**

cout<<"enter number:"; cin>>a; b=a;

output :

Enter number:

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

while(b!=0)

- New variable
used for storing the remainder and it will not use garbage value so we are using**d***(d=0).*

int d; d=0;

- original data of
that comes in**b**and add up with**d**because c stores the result values.**C**d=b%10; c=c+d;

- here after dividing the number by
we get all digits except last digit.**10**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**is not false and show output in**condition**.**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