-1

I just want to print an array 7x7 in c language which will look like this.

1 
1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1 
1 5 10 10 5 1 
1 6 15 20 15 6 1 

This is my code and i cant find the mistake.

#include <stdio.h>
int main()
{   
int P[7][7],i,j;
for (i=0; i<7; i++)
 {
 for (j=0; j<7; j++)
    {
    if (i=j) P[i][j]=1;
    if (i<j) P[i][j]=0;
    if (i>j && j!=0) P[i][j]=(P[i-1][j] + P[i-1][j-1]);
    if (j=0) P[i][j]=1;
    }
}
for (i=0; i<7; i++)
{
    for (j=0; j<7; j++)
    {
    if (P[i][j]=0) printf (" ");
        else printf ("%d ",P[i][j]);      
    }
printf ("\n");
}
}

Thanks in advance

haccks
  • 100,941
  • 24
  • 163
  • 252

2 Answers2

3

Your if statements have = (the assignment operator) rather than == (equality testing), for one thing. It's good to compile with gcc -Wall flag for such warnings. Also, since main should return an int, it would be good to have a return statement at the end...

kbshimmyo
  • 588
  • 4
  • 13
  • +1 for mentioning -Wall and `main` should always return int. Seen far too many people using `void main` these days – Yick Leung Dec 19 '13 at 20:30
  • Thanks! I meant a weaker version - that if it's declared as `int`, it better return `int`. What is the big reason for `int main` as opposed to `void main`? (Personally I use `int` to remind myself to check that the function is completely written. I use returned values from non-main routines for error-checking, but haven't done that on main...) – kbshimmyo Dec 19 '13 at 20:34
  • 1
    I think `void main` is not valid C code even if it works okay. From places that I've read: http://stackoverflow.com/questions/9356510/int-main-vs-void-main-in-c – Yick Leung Dec 19 '13 at 20:38
  • Hm, interesting. Thanks for the link; I'll read it later today. For defying the (modern) standards, K&R has bare-bones examples of working code that don't even specify a type for main (and don't explicitly include any headers). – kbshimmyo Dec 19 '13 at 20:44
  • You're welcome. I've never read K&R, but do they use `void main` in the book? – Yick Leung Dec 19 '13 at 20:49
  • Not explicitly so, but unspecified type (which defaults to `void`? I'm not sure): `main() { printf("hello world\n"); }` – kbshimmyo Dec 19 '13 at 20:51
  • Yeah I think it might be hinting to `void`. Or maybe `int` was not invented yet back then, I'll read it in the near future... Anyways, Cheers. – Yick Leung Dec 19 '13 at 20:58
1

There is great difference between assignment operator = and equality operator ==. = operator assign the value of the right operand to its left operand while == compares the equality of both the left and right operands. Change = to == in all of your if statements.

if (i == j) P[i][j]=1;
if (i < j) P[i][j]=0;
if (i > j && j != 0) P[i][j]=(P[i-1][j] + P[i-1][j-1]);
if (j == 0) P[i][j]=1;  

and

if (P[i][j] == 0) printf (" ");
    else printf ("%d ",P[i][j]); 
haccks
  • 100,941
  • 24
  • 163
  • 252