Aris
Aris

Reputation: 1

how to left align a set of characters in C

I am new to C and I have been trying to print a pyramid of * using for loops and printf() in a RIGHT ALIGNMENT manner; like this;

  *
 **
***

I can only do this

   *
   **
   ***

Upvotes: 0

Views: 2171

Answers (3)

machine_1
machine_1

Reputation: 4454

#include <stdio.h>
#include <string.h>

void f(int n)
{
    int x = 1 , y , var ;

    while( n > 0 )
    {
        for( var = n-1 ; var > 0 ; var-- )
        {
            fputc(' ',stdout);
        }

        for( y = 0 ; y < x ; y++ )
        {
            fputc('*',stdout);
        }

        fputc('\n',stdout);

        n--;

        x++;
    }
}

int main(void)
{
    f(3);

    return 0;

}

Upvotes: 0

Nitin Labhishetty
Nitin Labhishetty

Reputation: 1348

You can use printf format specifier tricks mentioned in the comments or you can do this using basic for loops. Break down the problem step by step. First a loop for given number of lines, then a loop for spaces in each line, then a loop for stars in each line. Here's the code:

#include <stdio.h>

int main(){
    int max_stars = 3;

    // for every line
    for(int i=1; i<=max_stars; ++i){

        // print max_stars - i spaces
        for(int j=1; j<= max_stars-i; ++j){
            printf(" ");
        }

        // print i stars
        for(int j=1; j<=i; ++j){
            printf("*");
        }

        //print a new line
        printf("\n");
    }
    return 0;
}

Upvotes: 1

MarineBiologist
MarineBiologist

Reputation: 55

#include<stdio.h>
    int main()
    {
        int i,j,k;

        for(i=1;i<=5;i++)
        {           
            for(j=5;j>i;j--)
            {
                printf(" ");
            }

            for(k=1;k<=i;k++)
            {
                printf("*");
            }

            printf("\n");
        }
        return 0;
    }

Here the first for-loop creates rows which are 5. Second for loop does the spacing and the third for loop prints the stars.

When i = 1; j goes from 5 to 2 and prints spaces. After this k=1 and it prints one star.

i = 1; j = 5,4,3,2; k = 1
i = 2; j = 5,4,3  ; k = 1,2
.
.
i = 5; j = 0; k = 1,2,3,4,5

Here "-" represents a blank space. So it goes down like this:

----*
---**
--***
-****
*****

Upvotes: 1

Related Questions