Convert Integer to String

Code

#include <stdio.h>

void print_integer_as_string(int num) {
    // Your logic here
    char str[10];
    int i=0;
    int negative=0;
    if(num==0)
    {
        printf("0");
        return ;
    }
    if(num<0)
    {
        negative=1;
        num=-num;
    }
    while(num>0)
    {
        str[i++]=(num%10)+'0';
        num=num/10;
    }
   
    if(negative)
    {
        str[i++]='-';
    }
    str[i] = '\0';
    for (int j = i - 1; j >= 0; j--) {
        printf("%c", str[j]);
        if (j > 0)
            printf(" ");  // space between characters
    }

}

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