How can I separate an integer into digits using for loop?
eg.
before: 123
after: 1 2 3
anyone can help me with that?

Recommended Answers

All 9 Replies

How can I separate an integer into digits using for loop?
eg.
before: 123
after: 1 2 3
anyone can help me with that?

Here is an idea. Convert to char *

Here is an idea. Convert to char *

Bad idea (unless you care to elaborate).

Often using division (/) and remainder (%) operations is used for homework.

#include <string.h>
#include <stdio.h>

int main()
{
   int num = 123;
   int i, result;
   char buff[11], temp[2] = {0, 0};
   
   sprintf(buff, "%d", num);
   
   for (i =0; i<strlen(buff); i++)
   {
        temp[0] = buff[i];
        result = atoi(temp);
        printf("%d\n", result);
   }
}

Compiled with gcc.

So a string, not a char*.

Avoid this idiom:

for (i =0; i<strlen(buff); i++)

And you don't really need to do atoi (which is declared in <stdlib.h>) if you just subtract '0'.

So a string, not a char*.

Avoid this idiom:

for (i =0; i<strlen(buff); i++)

And you don't really need to do atoi (which is declared in <stdlib.h>) if you just subtract '0'.

Don't understand what you trying to tell (my english is far from perfect) but whats wrong with strlen. You mean don't use it in for loop?

Don't understand what you trying to tell (my english is far from perfect) but whats wrong with strlen. You mean don't use it in for loop?

Right. As the loop condition, the strlen is called on each iteration of the loop. For longer strings, this makes something that looks [TEX]O(n)[/TEX] into something that is [TEX]O(n^2)[/TEX].

Right. As the loop condition, the strlen is called on each iteration of the loop. For longer strings, this makes something that looks [TEX]O(n)[/TEX] into something that is [TEX]O(n^2)[/TEX].

AH yes you are totaly right but I used it becouse the string length is very short in this case.

AH yes you are totaly right but I used it becouse the string length is very short in this case.

The point is that bad habits die hard. I know an experienced programmer who had exactly this bite him because of this habit. A programmer gets to used to doing this in small test cases, and then it looks normal and you've been using it forever -- and bang, your wonderful algorithm has horrible performance. So when I see this little bad habit, I try to nip it in the bud. Never get used to it and you'll never be bitten by it.

[edit]Besides, you don't even need strlen .

#include <stdio.h>

int main()
{
   char text[11];
   int i, num = 123, len = sprintf(text, "%d", num);
   for ( i = 0; i < len; ++i )
   {
      printf("%d\n", text[i] - '0');
   }
   return 0;
}

Thanks a million for your help! I've got the problem fixed. :cheesy:

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.