简体   繁体   中英

How can I display individual digits of an input number?

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;
}

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 .

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM