Home > Software design >  Recursive function for outputing string
Recursive function for outputing string

Time:11-21

I have a following code:

#include <stdio.h>
void recursion(char *ptr) {
    if(*ptr!='J') recursion(ptr  );
    printf("%c",*ptr);
}


void main() {
    char v[]="!zenaJ";
    char *ptr=v;
    recursion(ptr);
}

I would like to return Janez! trough the recursive function. I don't have any errors when compiling. When I run the program I get an error "Segmentation fault (core dumped)". What am I doing wrong?

CodePudding user response:

You are passing recursively the same pointer

if(*ptr!='J') recursion(ptr  );

because the value of the post-increment expression ptr is the value of the pointer before its incrementing.

The function written in C can look the following way

void recursion( const char *ptr ) 
{
    if ( *ptr )
    {
        recursion( ptr   1 );    
        putchar( *ptr );
    }
}

In C the function can look the following way

std::ostream & recursion( const char *ptr, std::ostream &os = std::cout ) 
{
    if ( *ptr )
    {
        recursion( ptr   1 );    
        os << *ptr;
    }

    return os;
}

Pay attention to that according to the C Standard the function main without parameters shall be declared like

int main( void )

and in C it can be declared like

int main()

CodePudding user response:

The increment of ptr occurs only after the recursive call for recursion. A simple fix should be:

#include <stdio.h>
void recursion(char *ptr) {
    if (*ptr != 'J')
    {
        char c = *ptr;
        ptr  ;
        recursion(ptr);
        printf("%c",c);
    }
    else
    {
        printf("%c", 'J');
    }
}


void main() {
    char v[]="!zenaJ";
    char *ptr=v;
    recursion(ptr);
}

CodePudding user response:

I strongly recommend to use the algorithm Depth first search to solve your problem.

#include <iostream>
#include <string>
#include <vector>
using namespace std;
const int maximumSize=10;
vector<int> visited(maximumSize, 0);
void depthFirstSearch(int currentIndex, int previousIndex, string input)
{
    if(visited[currentIndex]==1)
    {
        return;
    }
    visited[currentIndex]=1;
    for(int nextIndex=currentIndex; nextIndex<input.size();   nextIndex)
    {
        if(nextIndex==previousIndex)
        {
            continue;
        }
        depthFirstSearch(nextIndex, currentIndex, input);
    }
    cout<<input[currentIndex];
    return;
}
int main()
{
    string inputString="!zenaJ";
    depthFirstSearch(0, -1, inputString);
    return 0;
}

Here is the result:

Janez!
  • Related