-2

Hi is there way to check that your code is Recursion or not in c++? I write code but someone tell me that it isn't Recursion. I want to make sure.

#include <iostream>
#include <conio.h>

using namespace std;

bool winding(string str, int len) {
    int counttrue = 0;
    for(int i = 0; i < len; i++){
        if(str[i] == '1') counttrue++;
        else if(i != len - 1 && str[i] == '0' && str[i + 1] == '0') {
            counttrue += 2; i++;
        }
    }
    return (counttrue == len);
}


int main() {
  string strwinding;
  cin >> strwinding;
  cout << winding(strwinding, strwinding.length()) << endl;
  cout << "Continue...";
  getch();
  return 0;
}
  • 7
    Recursion is when a function calls itself. This is not the case here. – kebs Oct 04 '21 at 07:19
  • @kebs Should I change all the code now? –  Oct 04 '21 at 07:21
  • 2
    Depends on your assignment. Do you need to write a recursive function, then yes winding should call itself. And make sure you have a good stop condition. – Pepijn Kramer Oct 04 '21 at 07:25
  • 1
    Sounds like you are fishing for an answer to an assignment..? :) Look up recursion, there are a multitude of great articles out there. If you want to understand algorithms look up keywords such as "iteration" and "recursion" and their differences - it's quite fundamental knowledge in CS. – alexpanter Oct 04 '21 at 08:05
  • I strongly recommend removing the two lines `#include ` and `using namespace std;`. See also: [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). As for ``, you simply don't need it. Everything you need for input and output is already in ``. `conio.h` is a header specific to old MSDOS, and including it will prevent your code from compiling on most modern computers. – Stef Oct 04 '21 at 08:17

2 Answers2

2

A recursive function calls itself, and yours doesn't, so it's not recursive.

Assuming that the definition of a "winding" string is

  • The empty string, or
  • A 1 followed by a "winding" string, or
  • 00 followed by a "winding" string,

a straightforward translation could look like this:

bool winding(const string& str, int index)
{
    return index >= str.size()
        || ((str[index] == '1') && winding(str, index+1))
        || ((index < str.size() - 1)
            && str[index] == '0'
            && str[index+1] == '0'
            && winding(str, index+2));
}

// ...

cout << winding(strwinding, 0) << endl;

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
1

A recursive function is a function that calls itself, like for instance:

int fac(int x)
{
  if (x <= 1) return 1; else return x * fac(x - 1);
}

You can easily check if a function is recursive if you create a breakpoint at the beginning of the function and see if this breakpoint is reached more than once if you call the function from outside once.

Adok
  • 49
  • 7