Recursion help

Am I doing this right?

I am trying to practice recursion and what I did here was re-write an iterative function into a recursive one.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>

using namespace std;

void addOne(int a[])
{
    for(int i =0; i < 5; i++)
    {
        a[i] = a[i]+1;
    }
}

void addRec(int a[], int start, int end)
{
    if(start >= end)
    {
        return;
    }
    a[start]= a[start] +1;
    start++;
    addRec(a, start, end);
}

int main()
{
    int a[5] = {0,1,2,3,4};

    //addOne(a);
    addRec(a, 0, 5);

    for(int i = 0; i < 5; i++)
    {
        cout << a[i] << " ";
    }
}
Last edited on
Yes, that is a perfectly good way of doing recursion. However as usual, I'd like to point out that you should use prefix increment. Also, my inner grammar nazi is forcing me to tell you that you used the wrong "practise", the verb has an s and the noun has a c.
Thanks for the feedback and I've actually never have seen "practice" spelled "practise." But I will look that up right now.
Last edited on
I see no need for the increment operator being used on start here as the variable is not being used after the recursive call is made.

1
2
3
4
5
6
7
8
void addRec(int a[], int start, int end)
{
    if(start < end) // invert logic to avoid unnecessary return
    {
        ++a[start]; // use increment operator here (as just adding 1)
        addRec(a, start + 1, end); // but just just add 1 here
    }
}


Andy

PS Regarding

my inner grammar nazi is forcing me to tell you that you used the wrong "practise", the verb has an s and the noun has a c.

According to http://en.wiktionary.org/wiki/practise practice is used as the verb form "almost universally" in the US.

And Google gives me 96,000,000 for "practicing" (with quotes) but just 16,600,000 for "practising", so it looks like the latter form is dying.
Last edited on
Alternatively:

1
2
3
4
5
6
7
8
void addRec(int* a, unsigned size)
{
    if (size)
    {
        ++(*a);
        addRec(a+1, size-1);
    }
}
And Google gives me 96,000,000 for "practicing" (with quotes) but just 16,600,000 for "practising", so it looks like the latter form is dying.

I'm sorry, but I personally believe that the British version (where there is a difference) is the correct version here because they are different words and the general rule is that words like practice/practise and licence/license follow the same pattern as advice/advise. Maybe it is dying, but in my opinion, that is more of a reason to start using it right because not using it right becomes ambiguous.
I'm sorry, but I personally believe


This thread is hardly the place to evangelize your beliefs about the English language.
Okay. Sorry. I usually resist from correcting people to non-Americanised spellings.
Cire, I think you'll find it's spelt "evangelise".

:)
Topic archived. No new replies allowed.