开发者

how to put a bracket for a number in pascal triangle?

Here's the question : highlight(by putting a bracket) the answer for C(n, k) in the triangle. I have constructed my code for my 11 line pascal triangle. but i can't be able to highlight C(n, k).

Here's what I've done.

#include<stdio.h>

int recursive(int n, int k);

int main(void)
{
    int row, space, column, b, x, y;

    printf("Pascal triangle with 11 rows : \n");
    printf("Enter the row and column that you would like to highlight on the triangle : ");
    scanf("%d %d", &x, &y);

    if (x > 11)
    {
          printf("Error! The row entered must be smaller than 11! \n ");
    }

    else if (y > x)
    {
        printf("Error! Column CANNOT more than number of row!\n");
    }

    else 
    {
        for(row = 0 ; row < 11 ; row++)
        {
            for(space = 30 - 3 * row ; space > 0 ; space--)
            {
                printf(" ");
         开发者_如何学C   }

            for(column = 0;column <= row; column++)
            {
                {
                if(column == 0 || row == 0)
                {
                    b = 1;
                }
                else
                {
                    b = ( b * (row - column + 1)/column );
                }
                printf("%6d", b);
                }

                if(row == x-1 && column == y-1)
                {
                    printf("(%2d)",recursive( row , column ));
                }
                else
                {
                    printf("%d ",recursive( row , column ));
                } 
            }
            printf("\n");

        }

    }

    return 0;
}

int recursive(int n,int k)
{
    if( k == 0 || k > n)
        return 0;
    else if( n == 1 && k == 1 )
        return 1;
    else
        return ( recursive( n - 1, k) + recursive( n - 1, k - 1) );
}

Can someone tell me where have I done wrong?


Since you're printing the first digit in a loop. You need to check if the iteration is the one you want to highlight (just like you did for the part where you print the second digit).

Instead of:

printf("%6d", b);

Change to:

if(row == x-1 && column == y-1){
    printf("(6%d", b);
}
else{
    printf("%6d", b);
}

Then change your original attempt (where you print last digits) to have a single closing parenthesis.

printf("%2d)",recursive( row , column ));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜