For example, if I have the number 142, how do I know it contains the digit 1, 4, and 2?

So far, I've worked out that
142/100 = 1
142 - (1*100) = 42
42/10 = 4
42 - (4*10) = 2

So i can just use a looping system. But is there a simpler solution to find the digits than the method shown above?

Recommended Answers

All 10 Replies

divide, then use modulus.

You can create a loop, where the value you divide by is decreasing power of 10

Or just get it as a string and see what it contains. For example :

string number;
cin >> number; //say user entered "123"
int  a = number[0] - '0'; //a = 1
int b = number[1] = '0'; //a = 2
int c = number[2] = '0'; //a = 3

We subtract '0' because its an char offset, to convert from char to int
decimal.

try this;)

# include <iostream>
using namespace std;
void main ()
{
	int n, r[10], q, i;
	cout <<"\n input a positive number:";
	cin  >>n;

	if (n < 0)
	{
		n=-n;
	}
	cout<<"\nthe separate digits of number "<<n<<" are:";
	for (q=n,i=1;q!=0;r[i++]=q%10,q=q/10);
	for(i=i-1;i>0;i--)
	{
		cout<<r[i]<<", ";
	}
}

sleepybug,
While that is a correct solution, it's a perfectly horrible piece of code to use as an example, especially for a beginner.

And probably not acceptable in industry, either.

And around here, we use int main( ) with a corresponding return statement at the end.

To me, it seems as though your teacher is trying to show you how to use the modulus operand. Since you know that the modulus essentially figures out the 'remainder' of the number that you divide, it would be logical that

123 % 10 =3

So now that you know that taking the modulus of any number will get you the 'ones' digit, you just need to figure out how to get the tens and hundreds digits. This is where you need to divide. So if you take 123 and divide it by 10, you will get 12 in the console. modulus this number, and you get 2.
By now you are probably getting the 'pattern' in which you must use. Here are some sample equations which may help you out:

123 % 10 = 3
(123 / 10) % 10 = 2
(123 / 100) % 10 = 1

This is exactly what vmanes had suggested, just a bit more elaborate.

>> While that is a correct solution

I beg to differ. Thats far from a correct solution.

>> While that is a correct solution

I beg to differ. Thats far from a correct solution.

What question are you responding to?

One point that I thought I ought to bring up is that if you have
a non integer number such as a decimal you can still find the digits but the stop condition is tricky

so while

int i(142), n(10);
int remainder =  i%10;
i = (i - remainder) /n;

can be put in a loop upwards you don't catch decimals if it is changed to double i(1.42) This makes the approach of using a string preferable
you can check for '-' and '.'
and either get the digits one at a time or if
this is an assignment convert it to a number
but now if

//need to include <string>
std::string number;
std::cin >> number;
int num_letters  = number.size();
if(num_letters > 0)
{
    if(number[0] == '-')
    {
        //minus
     }

 //search to find in string
   if(std::string::npos != number.find('.', 0))
   {
      // have a point
      int pos_of_point = number.find('.', 0);
    }
   
}

>> While that is a correct solution

I beg to differ. Thats far from a correct solution.

I will expand on why this is true in a second.

First an aside
(
firstPerson -> did you find thishttp://www.daniweb.com/forums/thread260788.html
I expected at least a put down for not getting your signature :)
)

back on topic:

for (q=n,i=1;q!=0;r[i++]=q%10,q=q/10);

There are several rasons why this is wrong

1 - it can overflow r[10]
2 - if you are not going make code readable why are you starting
from i = 1 and not i = 0;
3 - the compiler will not necessarily optimise the code correctly
4 - the only reason for reducing the number of lines of code is to
make it more maintainable and in this instance this is not the case
5 - example code should always be readable
6 - stop condition of != 0 on something that you are changing is dangerous > 0 is better as with n being negative there is a risk of %10 being not the digit -1%10 should return 9

there is a lot of hidden behaviour being used such as
q = q / 10 is relying on the fact that q = q/10 is performing a floor operation with it being an int. But mathematically this is not what the code is saying

in my opinion a for loop declaration should always have just 1 start condition;1 stopcheck condition; and a simple increment

if your stop condition is not to be calculated every cycle then a complex third term can lead to unpredictable behaviour and could cause an infinite loop.

If you think of a for loop as being a while loop I think that fewer ugly examples woud result

//for(int i(0), i < istop; ++i)
//initialise
int i(0);
while(i < istop /*check true to continue*/)
{
++i; //increment
}

therefore the for line should be more like:
although still ugly logic so don't directly use!!

int q = n;
for(int i = 1; i < 10; i++)
{
 r[i] = q%10;
  q = q/10;
  if(q <= 0)
 {
  break;
 }
}

this is clearly too much to go in a single line and be read by a person!

You can simply use String streams, for e.g:

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
stringstream ss;
string Digits;
int Number;

cout << "Enter some number: ";
cin >> Number;
cin.ignore();

ss << Number;
ss >> Digits;

cout << "\nThe number " << Number << " consists of " << Digits.length() << " digit(s), and they are:\n\n";

for(size_t n=0 ; n<Digits.length() ; n++) {
cout << Digits[n] << endl;
}

cin.get();
return 0;
}
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.