Convert Integer to String

Code

#include <stdio.h>

void print_integer_as_string(int num) {
    // Your logic here
    char buf[20] = {0};
    int i = 0;

    if (num < 0) {
        printf("%c ", '-');
        num *= -1;
    }
    
    if (num == 0) {
        printf("0");
    } else {
        while (num != 0) {
            buf[i++] = (num % 10) + '0';
            num /= 10;
        }
        i--;

        while (i >= 0) {
            printf("%c ", buf[i--]);
        }
    }
}

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

Solving Approach

%c : ascii, printf("%c", 2 + '0'); or printf("%c", '2');

%d : integer, printf("%d", 2);

 

 

Upvote
Downvote
Loading...

Input

123

Expected Output

1 2 3