-1

I am writing a code to rewrite an integer taken from user with spaces between it. For example 456 would give 4 5 6. This is my code, but its printing the integer in reverse with spaces. For example its printing 6 5 4 instead of 4 5 6. Where am i wrong?

#include<stdio.h>

int spc(int x);

int main() {
    int n1;

    printf("Enter Number:");
    scanf("%d", &n1);
    spc(n1);
}

int spc(int x)
{
    int rem,quo;
    do {
        rem = x % 10;
        printf(" %d",rem);
        quo = x / 10;
        x = quo;    
    } while(x % 10 > 0);
}
Ôrel
  • 7,044
  • 3
  • 27
  • 46
bizz123
  • 23
  • 3

1 Answers1

0

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

bruno
  • 32,421
  • 7
  • 25
  • 37
  • So you point out additional failures of the code, which OP has not noticed yet. That would be an enlightening comment. But How is it supposed to be an answer? (Not my downvote nevertheless.) – Yunnosch Apr 26 '20 at 08:47
  • What if there's no 0 in the number? – Hallah Apr 26 '20 at 08:49
  • @Hallah how I was able to give a so stupid definition before ???? – bruno Apr 26 '20 at 08:53