Align text to right in C

40,166

Solution 1

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

Check here live.

Solution 2

void staircase(int n) {
    int counter = n-1;
    for(int i = 1; i <= n; i++){
        for(int m = 0; m < counter; m++){
            printf(" ");
        }
        for(int a = 0; a < i; a++){
            printf("%c", '#');
        }
        counter--;
        printf("\n");
    }
}

If we call the function as staircase(6);

It prints:

     #
    ##
   ###
  ####
 #####
######

Solution 3

Aligning text right is done like that:

printf("%3s", some_text);

3 means that the max length of the line is 3.

Aligning text left is the opposite:

printf("%-3s", some_text);
Share:
40,166
Salman2013
Author by

Salman2013

Updated on August 06, 2022

Comments

  • Salman2013
    Salman2013 almost 2 years

    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!

  • Salman2013
    Salman2013 over 9 years
    Thanks for your posting. Hope this will help me out a little. Just curious if you have another solution that involves for loop? I do not want to use hard-coded. Thanks! Suggestion would be great!
  • alk
    alk over 9 years
    @Salman2013: "I do not want to use hard-coded." You do not want use what?