w3resource

C++ Exercises: Compute the sum of the digits of an integer using function

C++ For Loop: Exercise-84 with Solution

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

Pictorial Presentation:

C++ Exercises: Compute the sum of the digits of an integer using function

Sample Solution:-

C++ Code :

#include <iostream>
using namespace std;

    int sumDigits(int num1,int n) 
	{
        int sum = 0;
        while (num1 != 0) 
		{
            sum += num1 % 10;
            num1 /= 10;
        }
        return sum;
    }
 
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;
	cout<<" The sum of the digits of the number "<<n<<" is: " << sumDigits(num1,n) <<endl;
	}

Sample Output:

Compute the sum of the digits of an integer:                          
-------------------------------------------------                      
 Input any number: 255                                                 
 The sum of the digits of the number 255 is: 12

Flowchart:

Flowchart: Compute the sum of the digits of an integer using function

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C++ to compute the sum of the digits of an integer.
Next: Write a program in C++ to reverse a string.

What is the difficulty level of this exercise?



Share this Tutorial / Exercise on : Facebook and Twitter

C++ Programming: Tips of the Day

Which is faster: Stack allocation or Heap allocation

Stack allocation is much faster since all it really does is move the stack pointer. Using memory pools, you can get comparable performance out of heap allocation, but that comes with a slight added complexity and its own headaches.

Also, stack vs. heap is not only a performance consideration; it also tells you a lot about the expected lifetime of objects.

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