Home > Back-end >  i tried solving this question and im not getting it
i tried solving this question and im not getting it

Time:04-08

I have added this logic to create right angle and i expect this output

10  
9  4 
8  5  3
7  6  2  1

but i'm getting

1
3   2
4   5  6
10  9  8  7

how can i fix this this?

and this is my code

#include<stdio.h>
int main()
{
   int n, r, c;
   int a=1, b;

   printf("Enter number of rows: ");
   scanf("%d",&n);

   for(r=1; r<=n; r  )
   {
     b=a r-1;
     for(c=1; c<=r; c  , a  )
     {
       if(r%2==1) printf("]",a);
       else printf("]",b--);
     }

     printf("\n");
   }

   return 0;
}

CodePudding user response:

Here is my solution:

In order to calculate the individual numbers, I first make a function get_highest_value_in_column, which calculates the highest value in a given column. I then calculate the individual numbers based on the position of the number in the column, taking into account whether the column is an even column (which has descending numbers) or an odd column (which has ascending numbers).

#include <stdio.h>

int get_highest_value_in_column( int column )
{
    return column * ( column   1 ) / 2;
}

int main( void )
{
    int n;

    //set variable "n" based on user input
    printf( "Enter number of rows: " );
    scanf( "%d", &n );

    //print one row per loop iteration
    for ( int i = 0; i < n; i   )
    {
        //print one number per loop iteration
        for ( int j = 0; j <= i; j   )
        {
            //add a space between numbers
            if ( j != 0 )
                putchar( ' ' );

            //find value of highest number in column
            int num = get_highest_value_in_column( n - j );

            //adjust number depending on position in column
            if ( j % 2 == 0 )
                //even row
                num -= i - j;
            else
                //odd row
                num -= n - 1 - i;

            //print the calculated number            
            printf( "=", num );
        }

        //print newline character to end the row
        putchar( '\n' );
    }
}

This program has the following output:

Enter number of rows: 4
 10
  9   4
  8   5   3
  7   6   2   1
Enter number of rows: 5
 15
 14   7
 13   8   6
 12   9   5   2
 11  10   4   3   1
Enter number of rows: 6
 21
 20  11
 19  12  10
 18  13   9   4
 17  14   8   5   3
 16  15   7   6   2   1
  •  Tags:  
  • c
  • Related