Convert Integer to String

Code

#include <stdio.h>

void print_integer_as_string(int num) {
    char buffer[12];   // Enough for 32-bit int (-2147483648)
    int i = 0;
    int isNegative = 0;

    if (num == 0) {
        printf("0\n");
        return;
    }

    if (num < 0) {
        isNegative = 1;
        num = -num;
    }

    // Convert digits to characters (in reverse order)
    while (num > 0) {
        buffer[i++] = (num % 10) + '0';
        num /= 10;
    }

    if (isNegative) {
        buffer[i++] = '-';
    }

    // Print characters in correct order with spaces
    for (int j = i - 1; j >= 0; j--) {
        printf("%c", buffer[j]);
        if (j > 0) {
            printf(" ");
        }
    }
    printf("\n");


}

int main() {
    int num;
    scanf("%d", &num);
    print_integer_as_string(num);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

123

Expected Output

1 2 3