Daggerhunt Daggerhunt - 1 month ago 9
C Question

a.exe has stopped working

#include<stdio.h>
#include<conio.h>
#include<string.h>
char *createP(int);
int main()
{
int n,i;
char str[100];
printf("int n = ");
scanf("%d",&n);
printf("string str = ");
scanf("%s",&str);
if(n>40)
return -1;
for(i=0;i<strlen(str);i++)
if(str[i]=='X' || str[i]=='Y' || str[i]=='Z')
continue;
else
return -1;
char *P;
P=createP(n);
printf("The generated string is = %s",P);
return 0;
}
char *createP(int n)
{
if(n==0)
return "X";
if(n==1)
return "Y";
if(n==2)
return "Z";
if(n>2)
return strcat(createP(n-2),createP(n-3));
}


I am trying to create a string for the following question :

P(0) = 'X'

P(1) = 'Y'

P(2) = 'Z'

P(n) = P(n-2) + P(n-3), n>2
where + denotes string concatenation.
I am using recursion (which looks quite obvious) for this problem.But my .exe is not working.

Guy Guy
Answer

You need to create a dynamic list, using only char *P don't let you use it as string at all.

Try to declare char P[100] , and at the end of the recursion put \0 char.

EDIT:

something like that:

void createP(int n,int index)
{
    if(n==0)
            P[index] = "X";
            return ;

    if(n>2)
        return strcat(createP(n-2,index + 2),createP(n-3,index + 3));
}

While P is global string, and index start with 0.

Comments