cstringoutput

Align text to right in C


I am little struggling how to make my output to show like this:

  a
 aa
aaa

My current output shows this instead:

a
aa
aaa

Below are my code:

void displayA(int a){
    for(int i = 0; i < a; i++)
        printf("a");
}

int main(void){
    displayA(1);
    printf("\n");
    displayA(2);
    printf("\n");
    displayA(3);
    printf("\n");
    return 0;
}

Any suggestion? Thanks.

Thanks for the answer. I realized that my coding logic was wrong. Using the suggestion below helped me figure it out. Thanks!


Solution

  • You can use printf("%*s", <width>, "a"); to print any text right aligned by variable no. of spaces.

    Check here live.