Strange code. What is the " || i == 0" for? The program is fine without it. I could understand if it was " || i == j" but that is also unnesessary.
And it seems just overly "clever", especially in the "coef = coef * (i - j + 1) / j". Ugh!
I'd split the calculation of coef out into a very simple function:
#include <stdio.h>
int coef(int i, int j) {
if (j == 0 || j == i)
return 1;
else
return coef(i-1, j) + coef(i-1, j-1);
}
int main() {
int rows, space, i, j;
printf("Enter number of rows: ");
if (EOF == scanf("%d", &rows)) return 1;
for (i = 0; i < rows; i++) {
for (space = 1; space <= rows - i; space++) printf(" ");
for (j = 0; j <= i; j++) printf("%4d", coef(i, j));
printf("\n");
}
return 0;
}
You can think that coef() will be inefficient. You're unlikely to be using a big enough value of rows that this will matter, but if you are then you can memoize the results:
#define MAXROWS 1024
int coefs[MAXROWS][MAXROWS]; // initialized to 0s
int coef(int i, int j) {
if (coefs[i][j] != 0) return coefs[i][j];
return coefs[i][j] = (j == 0 || j == i) ? 1 : coef(i-1, j) + coef(i-1, j-1);
}
This will about as fast as the original code -- or even faster as there is no multiply or divide. Of course it will use more RAM. Tradeoffs :-)