hi guys i need a little hint on how to break an integer into its component
so if you have like 1567 i need to get 4 integers with 1,5,6,7. Thank you

Recommended Answers

All 6 Replies

(1567 / 1 ) % 10 = 7
(1567 / 10 ) % 10 = 6
(1567 / 100 ) % 10 = 5
(1567 / 1000) % 10 = 1

See a pattern?

Also you can do it with string.

len = sprintf(buff, "%d", num);
   
   for (i=0; i<len; i++)
   {
      printf("%d\n", buff[i] - '0');
   }

Where num is in your case 1567.

Thank you so much. Looks so simple :) but i just cant make program run properly. I have no clue how to make intSum = 0; in the loop, so everytime you have clean variables.

#include <iostream>
using namespace std;

int main()
{
    int intInpt, i;
    int intNumb, intPowr, intSum;
    intPowr = 1;
    i=1;
    cout << "Enter an integer number (0 to stop): ";
    cin >> intInpt;
    intSum = 0; 
    
    do {
       intNumb = (intInpt / intPowr) % 10;
       intSum = intSum + intNumb; 
       intPowr = intPowr * 10;
       
       if (intNumb == 0)
       {
       cout << "Sum of digits is :" << intSum << endl; // displays result when int = 0
       cout << "Enter an integer number (o to stop): ";
       cin >> intInpt;

       }
       if (intInpt == 0)
       {
        i=0;
        }
        
    } while (i != 0);
    system("PAUSE");
    return (0);
}

I have no clue how to make intSum = 0; in the loop, so everytime you have clean variables.

Just assign it zero here. You will also have to assign 1 to intPowr also.

if (intNumb == 0)
       {
            cout << "Sum of digits is :" << intSum << endl; // displays result when int = 0
            cout << "Enter an integer number (o to stop): ";
            cin >> intInpt;
            intSum = 0; // Reinitialize
            intPowr = 1; // Reinitialize
       }

thank you again! my CS teacher couldn't figure it out so she allowed us to do this program with 10^9 limit. ;)

Just on an ending note, wanted to point out: system("pause") ; // dont use this function, its non portable and expensive call cin.get() ; // use this function instead

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.