Find The Sum of Digits in a Number Program in C++

            This is one of the most commonly asked program in a technical interview. The logic of this program is very simple we need to separate each digit from the original number and keep on adding them. Finally print the sum.

Let us take a number 5728. 
Now, the sum of all digits of 5728 will be 5 + 7 + 2 + 8 = 22.




//Program to print Sum of Digits

Logic : 

  • Input Number.
  • Take a loop repeat until the number exist.
  • Separate each digit.
  • Calculate the sum.
  • Print the sum.

Code : 


#include<bits/stdc++.h>
using namespace std;

int main()
{
    int n,sum=0;
    cin>>n;
    while(n)
    {
        sum+=n%10;
        n/=10;
        
    }
    cout<<sum;
    return 0;
}

***


!! SUBSCRIBE FOR MORE CODES & VIDEOS !!

Post a Comment

0 Comments