-2

This code basically computes nCr to print a pascal's triangle.

 #include <stdio.h>

 int nCr(int n,int r){
     if (r == 0 || r == n || n == 1 || n == 0){
        return 1;
 }
 else{
    return nCr(n-1,r) + nCr(n-1,r-1);
 }
}

How would this function be turned into an iterative version?

I forgot to mention this before, but the solution has to be without using lists, to somehow, convert this exact recursive logic to an iterative one.

azman
  • 3
  • 3
  • Just think about what happens in every recursion step and implement a loop that behaves like that. You maybe need a store to hold the values of iteration data. This data is stored at the stack when using recursion. Happy engineering! – Tom Schardt Nov 18 '17 at 10:18
  • Draw Pascals triangle on a piece of paper. Try to "walk" from its start to a specific value. During said "walk", consider what values you need at each step, and when those values have finished serving their purpose and can be discarded. Then write this walk with a loop and a couple of variables. – StoryTeller - Unslander Monica Nov 18 '17 at 10:39

1 Answers1

0
#include <stdio.h>

int main(void) {

    int n,r;
    scanf("%d%d",&n,&r);

    int mem[n+1][r+1];

    int i,j;

    for(i=0;i<n+1;i++)
    {
        for(j=0;j<r+1;j++)
        {
            if (j == 0 || j == i || i == 1 || i == 0)
                mem[i][j]=1;
            else
                mem[i][j]=mem[i-1][j]+mem[i-1][j-1];
        }
    }

    printf("%d",mem[n][r]);


    return 0;
}

I have used a 2D-array to save values so that i can use them instead of calling the function again and again. I have used Dynamic Programming concept. Please study about it to understand the code.

anupam691997
  • 310
  • 2
  • 8