Hello everyone, i'm new to programming.. and i'm stuck at a problem.. I want my program to identify the separate digits in a given number, like if i input 4692, it should identify the digits and print 4 6 9 2. And yeah, without using arrays.. Thanks in advance!
+21
A:
A perfect recursion problem to tackle if you're new to programming...
4692/1000 = 4
4692%1000 = 692
692/100 = 6
692%100 = 92
92/10 = 9
92%10 = 2
You should get the idea for the loop you should use now, so that it works for any number. :)
Suvesh Pratapa
2009-06-11 13:45:36
4692%1000 = 692, not 2.4692/1000 = 4, not 469.
chocojosh
2009-06-11 14:42:59
Yeah, +1 your answer is good because it leads to the answer rather than just solving the homework, but please correct your numbers!
Jason Cohen
2009-06-11 14:44:19
The problem with typing too fast, is I type faster than I think sometimes. ;) Corrected!
Suvesh Pratapa
2009-06-11 14:48:14
This works fine, unless there is a zero!
micmoo
2009-09-29 23:46:25
A:
Haven't written C code in year, but this should work.
int i = 12345;
while( i > 0 ){
int nextVal = i % 10;
printf( "%d", nextVal );
i = i / 10;
}
Babak Naffas
2009-06-12 00:01:04
This is completely wrong. You print the value of `i` 5 times: "123451234123121". Even if you print `nextVal` instead of `i`, you're doing it in the wrong order and will print "54321".
Jacob
2009-09-28 23:23:54
A:
Here is a simple solution if you want to just print the digits from the number.
#include
/**
printdigits
*/
void printDigits(int num) {
char buff[128] = "";
sprintf(buff, "%d ", num);
int i = 0;
while (buff[i] != '\0') {
printf("%c ", buff[i]);
i++;
}
printf("\n");
}
/*
main function
*/
int main(int argc, char** argv) {
int digits = 4321;
printDigits(digits);
return 0;
}
rjoshi
2009-09-29 18:15:12
You don't need 128 characters to print an integer. Also, why initialize `buff` if you're just going to overwrite it with `sprintf()` later? Also, why do you have `char *p` if you never use it?
Chris Lutz
2009-09-29 18:21:16
ya, earlier I was planning to iterate using pointer so I have char *p.Regarding size, he did not mentioned length of numbers so to be on safe size, used 128.
rjoshi
2009-09-29 18:26:53
An `int` can only hold numbers up to 4 billion on most platforms, so you should be safe with 10 digits (11 characters with the nul-terminator). If you're worried about 64-bits, that's still only around 20 to 25 characters.
Chris Lutz
2009-09-29 18:30:29
A:
I think the idea is to have non reapeating digits printed (otherwise it would be too simple)... well, you can keep track of the already printed integers without having an array encoding them in another integer.
some pseudo C, to give you a clue:
int encoding = 0;
int d;
while (keep_looking()) {
d = get_digit();
if (encoding/(2**d)%2 == 0) {
print(d);
encoding += 2**d;
}
}
fortran
2009-09-29 18:38:12