0
    #include <iostream>
using namespace std;
int count(int V[],int n,int p){
    int res;
    if(n==0)
        return 0;
    res=count(V,n-1,p);
    if(V[n-1]==p)
        res++;
    return res;
}

The problem is to find how many times p appear in an array using recursion. My question is: We called the function directly after we made the initial condition res=count(v,n-1,p),when we call it doesn't it go back to if(n==0), the way the code is written it just calls it then continues. Sorry i dont know how to explain my question hope someone understands thank you.

Elio
  • 73
  • 9
  • How do you initially call the function? Have you tried to step through the code (and entering the recursive calls) with a debugger (which I highly recommend)? – Some programmer dude Nov 11 '18 at 14:21
  • No, I'm afraid your question is unclear. The recursive call does "go back to" the first statement in the function. That's what happens when anything calls this function. This is the first statement in the function, so it gets executed. – Sam Varshavchik Nov 11 '18 at 14:22
  • https://godbolt.org/z/T_dfRl should be clearer, if you understand recursion. – Passer By Nov 11 '18 at 14:22
  • 1
    Best thing you can do for yourself right now is to fire up a dedbugger, and step through the code (and observe the backtrace of your calls when you do). Learning to use a debugger is a crucial skill, so if you don't know how to use a debugger yet, you'd be killing two birds with one stone. – StoryTeller - Unslander Monica Nov 11 '18 at 14:22
  • If I'm reading your question correctly, you seem to think that initializing a `res` variable in an outer scope would somehow influence the local variable `res` in the function. That's not so. `res` is a new variable at every call. – Jesper Juhl Nov 11 '18 at 14:24

0 Answers0