0

I am trying to print a string in reverse using recursion. However, the program below does not work as expected. What is the cause?

#include <stdio.h>

int main()
{
    char arr[]="rama";
    fun(arr);
}

int fun(char *p)
{
    static int i=0;
    
    if((p[i]) == '\0')
       return;
    else
    {
        i++;
        fun(p[i]);
        printf("%c", p[i]);
    }
}
11
  • Using static variables in recursion is kind of "cheating". The task can be accomplished with pure recursion Commented Sep 1, 2021 at 17:00
  • why adding static is cheating ? Commented Sep 1, 2021 at 17:03
  • Because it is the same as global. It is defeating the whole idea of recursion. Commented Sep 1, 2021 at 17:03
  • 2
    @Ravi static variable here is the global variable, and global state is quite bad: softwareengineering.stackexchange.com/questions/148108/… Commented Sep 1, 2021 at 17:04
  • 1
    Ravi, Save your valuable time. Enable all compiler warnings to warn why fun(p[i]); is bad. Commented Sep 1, 2021 at 17:05

3 Answers 3

2

probably you're looking for:

void fun(char *p) {
    if (*p) {
        fun(p + 1);
        printf("%c", *p);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

The program passes a char type to the function in the recursive case, while you'd want this to be a pointer. Iterating over a string given only a single character is not possible, we need to know where we are in the string.

As pointed out by various comments, using static is missing the point of writing a recursive function as it effectively introduces a global variable. In fact, using an index variable is not necessary at all. You may simply use the pointer as an argument and parameter. Dereference it to obtain the character is currently points to, and increment it to make it point to the next character.

Corrected code, with a couple of improvements:

#include <stdio.h>

// Declare the function before it is used.
// It doesn't return anything, so the return type should be "void".
void fun(char *p);

int main(void) // Correct main signature when not using command line arguments
{
    char *arr = "rama"; // We are not modifying the string, so a pointer to a string literal will do
    fun(arr);
    putchar('\n'); // Print a newline at the end of the program
}

void fun(char *p)
{
    if (*p == '\0') // Get the character the pointer currently points to
        return; // No need for an else if we return here

    fun(p + 1); // Pass the increment pointer
    putchar(*p); // Print the dereferenced pointer. No need for printf if we're just printing a single char
}

Another option is to make the function tail-recursive (Inspired by a comment by Eugene Sh.). This requires an additional index parameter, but let's you print the final newline in de base case.

#include <stdio.h>
#include <string.h>

void fun(char *p, size_t idx);

int main(void)
{
    char *arr = "rama";
    fun(arr, strlen(arr) - 1);
}

void fun(char *p, size_t idx)
{
    // Happens in both the base case and recursive case
    putchar(p[idx]);

    // Base case
    if (idx == 0U)
    {
        putchar('\n');
        return;
    }

    // Recursive case
    fun(p, idx - 1);
}

6 Comments

You could add putchar('\n') in the base case condition inside fun to make it self-contained
@EugeneSh. This is not tail recursion. The program would print the newline first and then the reversed string.
@EugeneSh. In any case, it gave me the idea of writing a tail-recursive version as well. Thank you!
@yun surprisingly when I replace fun(p+1); with fun(p++); the program does not print anything why so? I though p+1 is same as p++ isn't it?
@Ravi p+1, ++p (pre-increment) and p++ (post-increment) are all different things. The first one evaluates to exactly that, leaving p itself unchanged. The second one first increments p (like in p = p + 1) after which its result is used. The third one does what the second one does, but in reversed order, i.e. the expression takes the value of p first, fun(p) is executed and afterwards p is incremented. In this case, p is never incremented in the recursion and the problem loops forever (or until stack overflow happens).
|
0

Your fun has return type int, but you are not returning any integer. You have to declare function before main, as body of fun is below main. fun have receiving type char * but you are sending char.

#include <stdio.h>
int fun(char *p);
int main(){
    char arr[]="rama";
    fun(arr);
}

int fun(char *p){
    static int i=0;
    if((p[i]) == '\0')
       return 0;
    fun((p+1));
    printf("%c", p[i]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.