Your Ad Here

Tuesday, February 24, 2009

Write a C++ program to find the sum of individual digits of a positive integer.

#include(iostream.h) // place this '<' & '>' instead of '(' & ')' before iostream.h
#include(conio.h)
void main(void)
{
int no, rem, sum=0;
clrscr();
cout<<"Enter the required number:";
cin>>no;
while(no>0)
{
rem=no%10;
sum=sum+rem;
no=no/10;
}
cout<<"Sum of individual digits of a positive integer is:"<< sum;
getch();
}

Output:-
here 'rem' means remainder

Enter the required number: 123
Sum of individual digits of a positive integer is: 6

Note:-If u have any doubt regarding this program or logic, please feel free to contact me.

12 comments:

  1. Thanks buddy!!! You ar a lyf saver!!! BLESS YOU!!!

    ReplyDelete
  2. when i enter the value of six digits like 123456 then why output is 0.. pls tell me...

    ReplyDelete
  3. But it cn't display the sum of individual digits so i suggest the program:-

    #include
    #include
    class sum
    {
    long int n,r,s;
    public:
    sum()
    {
    s=0;
    cout<<"enter the number";
    cin>>n;
    }
    void digit()
    {
    p:
    while(n>0)
    {
    r=n%10;
    s=s+r;
    n=n/10;
    }
    if(s/10!=0)
    {
    n=s;
    s=0;
    goto p;
    }
    }
    void display()
    {
    cout<<"the sum is:"<<s;
    }
    ~sum()
    { }
    };
    void main()
    {
    clrscr();
    sum su;
    su.digit();
    su.display();
    getch();
    }

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. please help me to write a program which show the sum of digits of a double type number and show two sums one for integers and one for decimal.

    ReplyDelete
  6. please show how to write a C++ program to find the sum of individual digits of a positive integers

    ReplyDelete
  7. Tell Hudson to show his big might C++ program to you tonight

    ReplyDelete