C Online Compiler
Example: Pascal's Triangle using Dynamic Programming in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Pascal's Triangle using Dynamic Programming #include <stdio.h> int main() { int rows = 5; // Number of rows to generate int triangle[rows][rows]; // 2D array to store triangle values printf("Pascal's Triangle (Dynamic Programming approach):\n"); // Step 1: Iterate through each row for (int i = 0; i < rows; i++) { // Step 2: Print leading spaces for (int space = 0; space < rows - i - 1; space++) { printf(" "); } // Step 3: Iterate through each element in the current row for (int j = 0; j <= i; j++) { // Step 4: Calculate element value if (j == 0 || j == i) { triangle[i][j] = 1; // Edges are always 1 } else { // Sum of two elements from the previous row triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j]; } printf("%d ", triangle[i][j]); // Print the calculated value } printf("\n"); // Move to the next line } return 0; }
Output
Clear
ADVERTISEMENTS