1

I'm beginner and try to understand how recursion works. what is the different of using while and if int the code? why if i use "if" it produce correct result? but "while" doesn't? while(*k) ,when it reach "\0" then it print only once then it goes back to while loop again
thank you so much for the help!!

 #include <stdio.h>
 #include <stdlib.h>
 void back(char*k){
     if(*k) // works
     //while(*k) ->not work??
         back(++k);
     printf("%c",*k);
 }

 int main()
 {
     char k[]="hellomynameis";
     back(k);
     printf("Hello world!\n");
     return 0;
 }

is there possible way to do same thing in c++ but using iterator?

#include <iostream>
#include <string>

using namespace std;

void backk(string a){
    string::iterator itr;
    for (itr=a.begin();itr!=a.end();itr++){
        if (*itr)
            backk(++itr);
        cout<<a; --> is this possible  ?

        //simple and fast solution 
        for (itr=a.end();itr!=a.begin();itr--){
            if(*itr)
                cout<<*itr;
        }
    }
}

int main()
{
    string a("hello my name is");
    backk(a);
    cout << "Hello world!" << endl;
    return 0;
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
fiksx
  • 176
  • 1
  • 15
  • How about `for (itr=a.rbegin();itr!=a.rend();++itr) std::cout << *itr;`? – JVApen Jan 05 '19 at 08:17
  • Use recursion **instead** of using a loop. In simple cases like this recursion is just a different kind of loop and the if statement controls whether the looping continues or not. Using recursion and a while loop makes no sense (in a simple example like this). – john Jan 05 '19 at 08:17
  • Read [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). Be aware of the [call stack](https://en.wikipedia.org/wiki/Call_stack). [Use the `gdb` debugger](https://sourceware.org/gdb/current/onlinedocs/gdb/) to run your program step by step, so you'll understand what is going on. – Basile Starynkevitch Jan 05 '19 at 08:17
  • @BasileStarynkevitch thankyou! im using codeblock but is gdb debugger for linux? – fiksx Jan 05 '19 at 11:16
  • I don't understand your question. First, I recommend using Linux to learn C programming, since Linux is very student- and developer- friendly (e.g. it has [valgrind](http://valgrind.org/) that is very handy). Then, I guess that [MinGW](http://www.mingw.org) will provide you a port of GCC and of `gdb` to Windows. However, I never used Windows in my life. At last [Code::Blocks](http://www.codeblocks.org/) is *not* a compiler (just an IDE) – Basile Starynkevitch Jan 05 '19 at 11:19
  • @BasileStarynkevitch thankyou so much but what is the advantages of using linux over windows? if i use linux can i understand how recursion, call stack and also inspect variables or debug program thoroughly? – fiksx Jan 05 '19 at 14:59
  • I am biased. I never used Windows. But, AFAIK, Linux is mostly made of free software (whose source code you can study, and that is an advantage) and Linux has [valgrind](http://valgrind.org/), and its `gdb` works well. See also [this](https://stackoverflow.com/a/54041928/841108) answer. However, recursion is a difficult concept. Read also [SICP](https://mitpress.mit.edu/sicp/) – Basile Starynkevitch Jan 05 '19 at 16:38

1 Answers1

1

About your first question on why while doesn't work, lets see how code runs in this case
Starting from a simple example lets say our char[] is only GH\0 for simplicity, Well, its a little bit hard to explain but lets try
at first back is called and k points to G, as it is not \0, back is called again with k being ++ed so it is pointing to 'H' and again it is not \0 so back is called with another ++k in which this time is \0, so while is not executed and printf does its job, now the execution return to second back call, where it was called with H input, but as we ++ed it, we moved it on the stack and now it is pointing to \0 again, so second printf runs, now only first back call is remained, guess where k is pointing to? right, it is pointing to H(dont forget ++), so again while is executed, but the input is ++k which in turn is \0, so the new called back immediately returns with a printf, again we are in first back call but this time is pointing to \0 so another printf and we are done,
to understand the sequence better i suggest run this code

#include <stdio.h>
#include <stdlib.h>
void back(char*k)
{
    printf("%c",'O');

    while(*k) //->not work??
    {
        back(++k);
    }

    printf("%c",'f');
}

int main()
{
    char k[]="he";
    back(k);
    return 0;
} 

the expected out put is OOOffOff

hessam hedieh
  • 780
  • 5
  • 18
  • thankyou so much, really help me to understand recursive. can i ask one more thing, after reached "\0" and executed printf and back to first back call where k pointing to h, is it still inside the while loop and do the call "back(++k)" again? so "while" will not become false until *k is "\0" ? it will keep call "back (++k)"? the different from "if" is if will control recursion until *k false so stop calling back(++k) and execute next line after each recursion call but "while " will keep call "back(++k)" until it reach "\0" ? – fiksx Jan 05 '19 at 11:09
  • @Vixf, Welcome, yes, thats it, `if` just checks if in the current call another call should be made or not, but `while` forces the string to go again and again in the function until null is reached – hessam hedieh Jan 05 '19 at 11:15
  • thankyou! may i know what program do you use to trace or debug simple program like this? – fiksx Jan 05 '19 at 11:31
  • @Vixf, I mainly develop C framework in embedded environments, and each platform has its own tool, but for example you provided I just used an [online C compiler](https://www.tutorialspoint.com/compile_c_online.php) , no debug tool, I just tried to understand how code flows by reading code and simplifying it, then tested it with `printf` outputs to make sure I was right, in this example IMHO, this was enough, but in complex problems, a good debug platform is essential, as I said I have no idea what to use for PC apps, (if u r curious, I am using Xillinx SDK as my mainly EDK for embedded :D) – hessam hedieh Jan 05 '19 at 11:39