Align text to the right in C

I'm struggling a bit on how to make my output look like this:

  a
 aa
aaa

      

My current output shows this instead:

a
aa
aaa

      

Below is 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? Thank.

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

+3


source to share


3 answers


You can use no printf("%*s", <width>, "a");

to print any variable-aligned text. spaces.



Check it out here live .

+9


source


Here the parameter w

defines the width of the character to align a

to



void displayA(int a, int w){
  int i;
  for(i = 0; i < w; i++) {
    if( i < w - a ) printf(" ");
    else printf("a");
  }
}

      

0


source


This might be helpful.

To print a drawing of a staircase:

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

      

Below are the codes:

#include<stdio.h>

void print(int n)
{   int i,j;
    for(i=1;i<=n;i++)
    {     printf("%*s",n-i,"");   //for right alignment by n-1 spaces.
         for(j=0;j<i;j++)
         {
                  printf("%s","#");    
         }   
         printf("\n");  
    }   
}    
int main(void)
{   
    print(6);   
    system("pause"); 
    return 0;   
} 

      

0


source







All Articles