Write a function which, given a number, prints it digit by digit with 1 blank space between digits.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>

void print_digits(int);

int main(int argc, char **argv)
{
    int number;
    printf("Enter a number: ");
    scanf("%d", &number);
    print_digits(number);
    return 0;
}

void print_digits(int number) {
    if (number < 0)
    {
       number *= -1;
       printf("- ");
    }
    if (number > 10)
    {
        print_digits(number / 10);
        printf(" ");
    }
    printf("%d", number % 10);
}

When you compile and execute the above program it produces the following result on Linux:

Enter a number: 23456789
2 3 4 5 6 7 8 9
Enter a number: -2345678
- 2 3 4 5 6 7 8

Brief Explanation

  • The program starts by requesting the user to enter a number.
  • Using the function scanf, the number is read and assigned to the variable number. scanf reads characters from the standard input, interprets them according to the specification in format, and stores the results through the remaining arguments. scanf stops when it exhausts its format string, or when some input fails to match the control specification.
  • Next, the recursive function print_digits is called, which recursively prints the number digit by digit with 1 blank space between digits. A recursive function is a function which either calls itself or is in a potential cycle of function calls.

Add comment


Security code
Refresh