Convert Integer to String

Code

#include <stdio.h>

void print_integer_as_string(int num) {
    // Your logic here

    // Handle zero case
    if(num == 0){
        printf("0\n");
        return;
    }

    // Handle negative numbers
    if(num < 0){

        printf("- ");
        num = -num; // Making the number positive
    }

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

    // Print digits in correct order
    for(int j = i-1; j >=0; j--){
        printf("%d", digits[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