Home > Software engineering >  How can I display individual digits of an input number?
How can I display individual digits of an input number?

Time:11-21

If I input this number: 1234, I want the output to begin with 1 2 3 4 not 4 3 2 1. How do I do this?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int numbers, count=0, num;
    printf("\nEnter numbers: ");
    scanf("%d", &numbers);
    while(numbers>0)
    {
        num = numbers%10;
        numbers = numbers/10;
        printf("%d", num);
    }
    printf("The total number of digits is: %d\n", num);
    return 0;
}

CodePudding user response:

One of the solutions is to use recursion.

#include <stdio.h>
#include <stdlib.h>

// prints reverse order and returns count of digits
int printrev(int numbers)
{
    if (numbers <= 0)
        return 1;
    int num = numbers % 10;
    int count = printrev(numbers / 10);
    printf("%d", num);
    return count   1;
}

int main()
{
    int numbers, count = 0, num;
    printf("\nEnter numbers: ");
    scanf("%d", &numbers);

    count = printrev(numbers);

    printf("\nThe total number of digits is: %d\n", count);
    return 0;
}

CodePudding user response:

This topic was already answered in this stackoverflow question. Also, an easier way is to create an array where you can save the digits inside of while loop and then print it backwards. But in this case it would need to declare an array a priori.

CodePudding user response:

How about to display character by character in string order?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int numbers = 0;
    printf("Enter numbers: ");
    scanf("%d", &numbers);

    char szNumber[16] = "";
    snprintf(szNumber, sizeof(szNumber), "%d", numbers);
    int i = 0;
    while (i < 16 && szNumber[i] != '\0')
    {
        printf("%c ", szNumber[i]);
          i;
    }

    return 0;
}

Try this online.

  •  Tags:  
  • c
  • Related