Convert Integer to String

Code

#include <stdio.h>

#include <stdio.h>

#include <stdio.h>

void print_integer_as_string(int num) {
    char str[12];  // enough for "-2147483648\0"
    int i = 0;
    int is_negative = 0;

    // Handle negative numbers
    if (num < 0) {
        is_negative = 1;
        num = -num;  // make it positive for digit extraction
    }

    // Handle zero explicitly
    if (num == 0) {
        str[i++] = '0';
    }

    // Extract digits in reverse order
    while (num > 0) {
        str[i++] = (num % 10) + '0';
        num /= 10;
    }

    // Add '-' if it was negative
    if (is_negative) {
        str[i++] = '-';
    }

    str[i] = '\0'; // null-terminate

    // Print in reverse (since digits are stored backwards)
    for (int j = i - 1; j >= 0; j--) {
        printf("%c ", str[j]);
    }

    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