0

I am trying to insert all Catalan number in array, but my code is not working.

  • Description: Insert the elements in the Catalan sequence in the array given initialized only for C[0].
  • Inputs: address of array
    • n: next position to be filled;
    • top: maximum number of entries to be computed.
  • Output:
    • int: number of elements in the array.
    • Side effects: update the elements of the array.

Code:

#include <stdio.h> 

#define MAX 6
int CatSeq (int CatArray[], int n, int top){
    int c;
    if (top == 1) CatArray[n]= 1; 
    else{ 
        for ( c = 0; c <= MAX; c++){
            CatArray[n] = 2 * (2*top - 1) * CatSeq(CatArray, n, top-1) / (top+1);
            n++;
        }
    }
    return n;
}
void PrintSeq(int Seq[], int top){
    int i; 
    for ( i = 1; i < MAX; i++)  
        printf("%d \n", Seq[i]);
}
int main(){
    int c = 0, n = 0 ;
    int CatArray[MAX];
    c = CatSeq(CatArray, n, MAX);
    PrintSeq(CatArray, c);
    return 0;
}
Guy Coder
  • 24,501
  • 8
  • 71
  • 136
nader
  • 1
  • 1
  • What exactly does "my code is not working" mean? Is it segfaulting? Not producing what you expect? – Drew McGowen Jul 31 '13 at 14:14
  • Also, I imagine the `for` loop in your `PrintSeq` function should start off `i = 0`, not `i = 1` – Drew McGowen Jul 31 '13 at 14:16
  • [Here](http://www.calcul.com/catalan-recursive) is an alternative method for computing catalan numbers, which doesn't involve division, and might be a bit simpler to implement. – Drew McGowen Jul 31 '13 at 14:23

1 Answers1

1

Array out of index error:

for ( c = 0 ; c <= MAX;c++){
                ^
                check loop

Correct is:

for ( n = 0 ; n < MAX; n++){

it should be n < MAX, since n could be passed in as non-zero to the function.

CatArray[n] = 2 * (2*top - 1) * CatSeq(CatArray, n, top-1) / (top+1);
                                                 ^
                                                here n is non-zero 

no need of c variable.

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208