yo not only write the digits in the reverse order, but your end condition
while(x % 10 > 0);
is wrong and stops the loop when you reach a '0'
Also the function must be void
because you never return a value, and you do not have to.
Always check if scanf was able to get expected value(s)
Can be :
#include<stdio.h>
void spc(int x);
int main() {
int n1;
printf("Enter Number:");
if ((scanf("%d", &n1) == 1) && (n1 >= 0)) {
spc(n1);
putchar('\n');
}
}
void spc(int x)
{
if (x >= 10)
spc(x/10);
putchar((x % 10) + '0');
putchar(' ');
}
If you want to also manage negative numbers still using only int :
#include<stdio.h>
void spc(int x);
int main() {
int n1;
printf("Enter Number:");
if (scanf("%d", &n1) != 1)
puts("invalid number");
else {
spc(n1);
putchar('\n');
}
}
void spc(int x)
{
if (x/10 != 0)
spc(x/10);
else if (x < 0)
fputs("- ", stdout);
putchar(((x < 0) ? -(x % 10) : x % 10) + '0');
putchar(' ');
}
Warning to not do -x
because the most negative int does not have its equivalent positive int.
bruno@bruno-XPS-8300:/tmp$ gcc f.c
bruno@bruno-XPS-8300:/tmp$ ./a.out
Enter Number:aze
invalid number
bruno@bruno-XPS-8300:/tmp$ ./a.out
Enter Number:0
0
bruno@bruno-XPS-8300:/tmp$ ./a.out
Enter Number:123
1 2 3
bruno@bruno-XPS-8300:/tmp$ ./a.out
Enter Number:-123
- 1 2 3
bruno@bruno-XPS-8300:/tmp$
If you have the external representation of the number we can imagine to not manage a number but just print the string in its order adding a space after each character, but this is probably to cheat
Note in my definitions I do not use printf
with a format like %d
because it is useless for a digit, and I do not want to use printf because this is to cheat considering the question