0

I'm very new to C, although I've done a decent amount of Java before. I'm making a basic Pascal's Triangle program and I've been looking at it for an hour trying to get it working. All the logic seems correct to me but I'll probably die before I realize what's wrong. Here's the program:

#include <stdio.h>
#include <stdlib.h>
double fact(int num);

int main()
{
    int row_index = 0;
    printf("Enter the row index : ");
    scanf("%d",&row_index);
    printf("\n");
    int i;
    double output1 = 0;
    double output2 = 0;
    double output3 = 0;
    double output4 = 0;
    double output5 = 0;
    int output6 = 0;
    for(i = 0; i <= (row_index + 1); i++)
    {
        output1 = fact(row_index);
        output2 = fact(i);
        output3 = row_index - i;
        output4 = fact(output3);
        output5 = output1 / (output2 * output4);
        output6 = (int)(output5);
        printf("%i ",output6);
    }
    return 0;
}

double fact(int num)
{
    double result;
    int i;
    for(i = 1; i <= num; ++i)
        {
            result = result * i;
        }
    return result;
}

The compiler is giving me no errors, and each every time I input a number it gives this as output:

Enter the row index : 6

-2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648
Spencer Hecht
  • 23
  • 2
  • 4
  • Numbers are less likely to go out of range if you can find a progressive algorithm which multiplies and divides a previous term, instead of trying to shoot the moon with a factorial function. Or, which builds an array by addition only of two previous array terms. – Weather Vane Feb 15 '17 at 23:40

2 Answers2

0

In double fact(int num), the variable result should be explicitly initialized. Also, I would suggest you to define both the return value of the function and variable result to int type.

See (Why) is using an uninitialized variable undefined behavior?.

Community
  • 1
  • 1
Neo X
  • 947
  • 7
  • 9
0

At a glance, there seems to be several issues.

First:

double fact(int num)
{
    double result;
    int i;
    for(i = 1; i <= num; ++i)
    {
    result = result * i;
    }
    return result;
}

result is not initialized to anything. Maybe you need to initialize it to 1?

for(i = 0; i <= (row_index + 1); i++)
{
    output2 = fact(i);
    output3 = row_index - i;
    output4 = fact(output3);
    output5 = output1 / (output2 * output4);
}

the first time around, i == 0; which means output2 at best will be 0 (assuming its automatically initialized to 0). If output2 == 0, output5 might be undefined. I say might because of double-precision numbers it may actually not be exactly 0.

Jorge Del Conde
  • 265
  • 1
  • 4