﻿ C++ Exercises: Compute the sum of the digits of an integer - w3resource

# C++ Exercises: Compute the sum of the digits of an integer

## C++ For Loop: Exercise-83 with Solution

Write a program in C++ to compute the sum of the digits of an integer.

Pictorial Presentation:

Sample Solution:-

C++ Code :

``````#include <iostream>
using namespace std;

int main()
{
int num1,sum,n;
sum=0;
cout << "\n\n Compute the sum of the digits of an integer:\n";
cout << "-------------------------------------------------\n";
cout << " Input any number: ";
cin>> num1;
n=num1;
while (num1 != 0)
{
sum += num1 % 10;
num1 /= 10;
}
cout<<" The sum of the digits of the number "<<n<<" is: " << sum <<endl;
}
``````

Sample Output:

``` Compute the sum of the digits of an integer:
-------------------------------------------------
Input any number: 25
The sum of the digits of the number 25 is: 7
```

Flowchart:

C++ Code Editor:

What is the difficulty level of this exercise?

﻿

## C++ Programming: Tips of the Day

How to replace all occurrences of a character in string?

std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.

```#include <algorithm>
#include <string>

void some_func() {
std::string s = "example string";
std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}
```

Ref: https://bit.ly/3niU71x