Created
December 6, 2011 18:27
-
-
Save titouanc/1439301 to your computer and use it in GitHub Desktop.
Triangle de Pascal (INFO2009-Repetition 4)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
int **triangle_pascal(int n); | |
int main(int argc, const char **argv){ | |
int n = (argc > 1) ? atoi(argv[1]) : 10; | |
int **triangle = triangle_pascal(n); | |
int x, y; | |
if (! triangle) | |
return 1; | |
for (y=0; y<n; y++){ | |
for (x=0; x<n; x++) | |
printf("%8d", triangle[x][y]); | |
printf("\n"); | |
} | |
for (x=0; x<n; x++) | |
free(triangle[x]); | |
free(triangle); | |
return 0; | |
} | |
int **triangle_pascal(int n){ | |
int **res = NULL; | |
int x, y; | |
if (n < 1) | |
return NULL; | |
//si erreur d'allocation, on renvoie NULL | |
res = malloc(n*sizeof(int *)); | |
if (! res) | |
return NULL; | |
for (x=0; x<n; x++){ | |
res[x] = malloc(n*sizeof(int)); | |
//si erreur d'allocation, on libere tout ce qui a ete alloue jusque la | |
//et on renvoie NULL | |
if (! res[x]){ | |
for (y=0; y<x; y++) | |
free(res[y]); | |
free(res); | |
return NULL; | |
} | |
} | |
res[0][0] = 1; | |
for (x=1; x<n; x++){ | |
res[x][0] = 1; | |
res[0][x] = 1; | |
} | |
for (x=1; x<n; x++) | |
for (y=1; y<n; y++) | |
res[x][y] = res[x-1][y] + res[x][y-1]; | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment