c - 使用函数的帕斯卡三角形

标签 c function loops logic pascals-triangle

well I've got it how to construct the pascal triangle and the code below is flawless but...in this code i am making the 1 to appear in first row by creating a new for loop especially for it... is there a way to generate pascal triangle without using an exclusive for loop for the 1 to appear in first... any help is much appreciated :)

//pascal triangle with ncr function
        #include <stdio.h>
        #include <conio.h>
        int ncr(int i,int j);
        int main()
        {
            int i,j,v,n,f,s;
            printf("Enter the number of rows required\n");
            scanf("%d",&n);
            f=n;
     //this is what i am exclusively using for printing 1 in 1st row
            for(;f>0;f--)
            {
                printf(" ");
            }
            printf("1\n");
     //is there a way to generate the above 1 using only the below for loop
            for(i=1;i<=n;i++)
            {
                for(s=n-i;s>0;s--)
                {
                    printf(" ");
                }
                for(j=0;j<=i;j++)
                {
                    v=ncr(i,j);
                    printf("%d ",v);
                }
                printf("\n");
            }
        }
        int ncr(int i,int j)
        {
            int k;
            float ans=1;
            for(;j>=1;j--)
                {
                    ans=((ans*i)/j);
                    i--;
                }
                k=ans;
                return(k);
        }

最佳答案

如果仔细观察,您会发现 ncr 函数是在 main 方法内部定义的。将 ncr 的实现移至 main 之外。

此外,@BLUEPIXY 注意到,您的 ncr 实现有多余的 ;:

int ncr(int i,int j); //<<right here
{
//...

编辑第二个问题的解决方案(参见 Pascal's Triangle on Wikipedia )

三角形的“第一”行实际上是第零行。您的外循环以 i = 1 开始,因此“第一”行包含 1C01C1。 “第一”行或第零行实际上应该只包含 0C0。新循环:

//notice how the i here has changed to 0
for(i=0;i<=n;i++)
{
    for(s=n-i;s>0;s--)
    {
        printf(" ");
    }
    for(j=0;j<=i;j++)
    {
        v=ncr(i,j);
        printf("%d ",v);
    }
    printf("\n");
}

关于c - 使用函数的帕斯卡三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33316318/

相关文章:

c - 使用函数将 char 数组解析为数组

c - 如何在C中使用while循环添加数组元素?

java - 如何在一个 hashmap 上设置 2 个迭代器

python - 如何从现有列表列表中创建第一个元素的新列表

c++ - ctags 没有索引类成员函数

c - dprintf 隐式声明警告

javascript - 验证日期

c - 函数内的函数参数

c - C中从套接字中读取消息

c - 我正在尝试编写一个函数,从给定的链表中删除所有奇数元素并返回一个地址