Skip to content

Instantly share code, notes, and snippets.

@watmough
Created January 5, 2012 23:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save watmough/1567842 to your computer and use it in GitHub Desktop.
Save watmough/1567842 to your computer and use it in GitHub Desktop.
Display a line of Pascals Triangle
/*
* Pascals Triangle in C
*
* Hacker News: http://news.ycombinator.com/item?id=3428984
*
*/
#include <stdio.h>
#include <stdlib.h>
long * next_line( long *line, int *length )
{
(*length)++;
long *next_line = (long*)malloc(sizeof(long)* *length);
int p=0;
for (; p<*length; ++p) {
if (p==0 || p==(*length)-1) {
next_line[p] = 1;
} else {
next_line[p] = line[p-1] + line[p];
}
}
free(line);
return next_line;
}
int main( int argc, char **argv )
{
if (argc!=2) {
printf("Usage:\n\t%s <n>\nDisplay nth line of Pascal's triangle.\n",argv[0]);
exit(1);
}
long *line = NULL;
int length = 0;
int n = atoi(argv[1]);
int i=0;
for (; i<n; ++i) {
line = next_line( line,&length );
}
for (i=0; i<length; ++i) {
printf ("%ld ",line[i]);
}
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment