Tuesday, 17 June 2014

C++ program to find sum of digits in a given number

C++ program to find sum of digits in a given number.


Method 1 : C++ program to find sum of digits of a number
#include<iostream>
using namespace std;
int main()
{
    int a,b=0,c;
    cout<<"Enter the number ";
    cin>>a;
    while(a)
    {
        b+=a%10;
        a/=10;
    }
    cout<<"Sum "<<b;
    return 0;
}



Method 2 : C++ program to find sum of digits of a number using recursion
#include<iostream>
using namespace std;
int digit(int n)
{
    if(n==0)
        return n;
    return n%10+digit(n/10);
}
int main()
{
    int n;
    cout<<"Enter number : ";
    cin>>n;
    cout<<"Sum of digits : "<<digit(n);
    return 0;
}



Method 3 : C++ program to find sum of digits of a number using tail recursion
#include<iostream>
using namespace std;
int digit(int n,int sum)
{
    if(n==0)
        return sum;
    digit(n/10,sum+n%10);
}
int main()
{
    int n;
    cout<<"Enter number : ";
    cin>>n;
    cout<<"Sum of digits : "<<digit(n,0);
    return 0;
}

No comments:

Post a Comment