a simple program that counts and sums digits. How can I make it work?

user1710386 picture user1710386 · Sep 30, 2012 · Viewed 16.9k times · Source

So I've to write a simple program(that loops) where you can enter an int and it spews out the number count and the sum of the numbers. Since I am such a tard when it comes to programming, I just scavenged the code online and tried to piece it together. I guess the sum block screws with n, but I am not really sure. Anyway, I would really appreciate it if somebody could point out mistakes and show me how can I make it work.

#include <iostream>
using namespace std;

int main()
{
    while(1)
    {
        int i,p,n,sum=0;  //sum block
        cout<<"enter an int: ";
        cin>>n;

        {
            while(n!=0)
            {
                p=n % 10;
                sum+=p;
                n=n/10;
            }
            cout<<"int digit sum: "<<sum <<endl;
        }
        {
            int count = 0;
            while(n)
            {
                n /= 10;
                ++count;
            }
            cout <<"number of digits: " << count << '\n';
        }
    }
}

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Sep 30, 2012

Since the loops that you are using are destructive (i.e. they make n go to zero by the end of the loop) you need to combine the two loops into one:

int sum=0, count=0;
while(n!=0)
{
    count++;
    sum += n%10;
    n /= 10;
}