Select Page

# C++ Program to calculate the sum of the digits of a number

by | Jan 28, 2023 | C++, C++ Programs

Home » C++ » C++ Programs » C++ Program to calculate the sum of the digits of a number

## Introduction

In this program, you will learn to calculate the sum of the digits of the integer value entered by the user in the C++ language.

For example, the number is 98542, and then this code will add all the digits of 98542 i.e., 9+8+5+4+2=28, and return 28 as output.

To understand the program, learn the following basic concepts of C++ programming

1. Operators

2. while and do-while loop

## Program

```#include<iostream>

using namespace std;

int main()

{

int n;

cout<<"Enter a integer: ";

cin>>n;

int rem=0; // rem is used for remainder

int sum=0;

while(n!=0)

{

rem=n%10; // fetching the last digit

sum=sum+rem; // rem is added to sum

n=n/10; // elimination of last digit

}

cout<<"Sum: "<<sum;

return 0;

}```

## Output ## Explanation

‘n’ will store the integer entered by the user.

int rem=0;

‘rem’ variable is initialized with a 0 value to find the remainder.

int sum=0; ‘sum’ variable is initialized with a 0 value to hold the sum of the digits.

The value of ‘n’ is 895412

while(n!=0)

the above condition is true

rem=n%10; this will return rem=895412%10=2

sum=sum+rem;

Since the sum is 0, therefore from the above statement, z=0+2=2

n=n/10; the value of ‘n’ is updated to 895412/10=89541, thus vanishes the last digit.

Again, the condition in the while loop will become true, and the same procedure will take place for n=89541

rem=89541%10=1

sum=2+1=3

n=89541/10=8954

Again, the condition in the while loop will become true, and the same procedure will take place for n=8954

rem=8954%10=4

sum=3+4=7

n=8954/10=895

Again, the condition in the while loop will become true, and the same procedure will take place for n=895

rem=895%10=5

sum=7+5=12

n=895/10=89

Again, the condition in the while loop will become true, and the same procedure will take place for n=89

rem=89%10=9

sum=12+9=21

n=89/10=8

Again, the condition in the while loop will become true, and the same procedure will take place for n=8

rem=8%10=8

sum=21+8=29

n=8/10=0

The loop gets terminated when n becomes equal to 0.

Thus ‘sum’=29

## Author

• A Full Stack Developer with 10+ years of experience in technical content creation.

• 