PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 16, 2022

[FIXED] How could I align my output to the center?

 August 16, 2022     alignment, c, for-loop, indexing, output     No comments   

Issue

    #include<stdio.h>
    int main()
    {
        int n ;
        printf("Input the number of rows: ");
        scanf("%d", &n);

        for(int i = 1; i <= n ; i++)
        {
            for(int j = 1 ; j <= i ; j++)
            {
                if(j == i + 1)
                {
                    break;
                }

                printf("%3d", j);
    
            }
            for(int  j = i - 1 ; j > 0; j--)
            {
                if(j == 0)
                {
                    break;
                }
                printf("%3d", j);
            }
            printf("\n");
            
        }
    }

Program session

Number of rows for this output n = 3

My output:   
            1
            1  2  1      
            1  2  3  2  1


Preferred output:   
                  1
               1  2  1      
            1  2  3  2  1
           

This here is an exercise where I have to print a pyramid of numbers where the central number of the pyramid is the number of the row. I understand the logic but as you can see I have not been able to fulfill the task successfully. Any tips?


Solution

As pointed out by @WeatherWane, you need to add logic to add extra spaces. If you notice carefully, number of spaces on each line(excluding padding you add with %3d is equal to 3 * (n - i)). You can create a simple method like this to add spacing:

void addSpaces(int N, int currentIndex, int padding) {
  for (int index = currentIndex; index < N; index++)
      for (int spaces = 0; spaces < padding; spaces++)
         printf(" ");
}

then you can call it from your first for loop like this:

  for(int i = 1; i <= n ; i++)
    {
      addSpaces(n, i, 3);
      for(int j = 1 ; j <= i ; j++)
        {
           // ...

I tested it and it seems to align it correctly:

c-posts : $ ./a.out 
Input the number of rows: 5
              1
           1  2  1
        1  2  3  2  1
     1  2  3  4  3  2  1
  1  2  3  4  5  4  3  2  1


Answered By - Rohan Kumar
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing