Home > Blockchain >  Recursion function C
Recursion function C

Time:10-04

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;
}

CodePudding user response:

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;

CodePudding user response:

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.

  • Related