-2

I'm new here and new in programming field too.
I was given a task to reverse a string using recursion and I build a program for it. But I'm not sure whether it is using recursion or not? Here's the code:

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

void reverse(char, long);

int main(){

  char i[100];
  long c;

  gets(i);
  c = strlen(i);

  reverse(i,c);
  return 0;
}

void reverse(char x[100], long y){

  printf("%c", x[y-1]);
  if (y>=0) {
      reverse(x, y-1);
  }
}

I just want to know whether this program is using recursion for reversing the string or not?

5
  • 2
    prototype of the function does not match the actual one Commented Oct 30, 2015 at 8:18
  • 2
    Possible duplicate of Reverse a string using a recursive function Commented Oct 30, 2015 at 8:19
  • 1
    It is but y >= 0 looks bad and you should only decrement y once. Commented Oct 30, 2015 at 8:20
  • Thanks @Haris for quick reply, but my question is different. Commented Oct 30, 2015 at 8:20
  • 1
    If a function is calling itself, directly or indirectly (e.g. function f call function g which calls f) then that's the very definition of recursion. Commented Oct 30, 2015 at 8:22

2 Answers 2

0

A straight answer would be yes, your program is using recursion. As the function is calling itself.

But, i would also like to point out that your program is not reversing the string, it is just printing the string is the reverse order.

You can go through this answer to see how you would actually reverse the string, and not just print it in the reverse order.

Note:

Dont use gets(), it is deprecated. use fgets() instead.

Sign up to request clarification or add additional context in comments.

5 Comments

Among others, your answer seems to me quite satisfactory. Yeah, my code does use recursion but it is not using recursion for reversing the string. If you can help me then it would be nice. Thanks!
@AKB, help you in what?
tell me how to reverse a string using recursion. which part of my code has to be changed?
This is an entirely new question. You should make a new post for this. SO is not a fast food counter where you can keep ordering items off the dollar menu as much as you want.
@AKB i agree with Tim, you can ask another question asking what has to be changed to make it actually reverse the string, but i suggest trying something yourself first.
0

A method calling itself is generally considered to be recursive, so your code is indeed recursive

3 Comments

Because it's short? But it answers the exact question.
I thought he was looking for code as well, my mistake ^ ^
@TimBiegeleisen only if my code is not using recursion.

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.