In this tutorial you will learn about the C++ Programs to Calculate Sum Of Digits and its application with practical example.
C++ Program to Print Sum of Digits
In this tutorial, we will learn to create a C++ program that will Print Sum of digits in a given Number using C++ programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C++ programming topics:
- Operators in C++ Programming.
- Basic Input and Output function in C++ Programming.
- Basic C++ programming.
- While loop in C++ programming.
- Conditional Statements in C++ programming.
- Arithmetic operations in C++ Programming.
Program to Print Sum of digits in a given Number
In c++ programming, we will make a program in today’s tutorial. We will take integer input from the user and find Sum of digits in a given number with the help of a program.
With the help of this program, we can Print Sum of digits in a given number.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declaring the variables required for the program. 2. Taking the input number from the user for the program. 3. Calculating the total number of digits in the numbers. 4. Calculating the sum of all the numbers in the given number. 5. Printing the result numbers. 6. End Program |
Program to Print Sum of digits in a given number:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> using namespace std; int main() { //declaring the variables required for the program int n,sum=0,m; //n = it will hold the integer value for number input from the user //sum = it will hold the integer value for sum of digits //it will hold the integer value for //taking input number from the user cout<<"Enter a number: "; //scanning the input number from the user cin>>n; //calculating the sum of the number //of digits of the given number while(n>0) { m=n%10; sum=sum+m; n=n/10; } //printing the sum of digits of given input cout<<"Sum is= "<<sum<<endl; return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- n = it will hold the integer value of the input.
- sum = it will hold the integer value for sum.
- m = it will hold the integer value.
Input number from the user.
Program Logic Code.
Printing output for sum the digits.