Does anyone have a good website I can go to. I would like to know the difference between recursion and repetition.
Printable View
Does anyone have a good website I can go to. I would like to know the difference between recursion and repetition.
Have you looked at the programming tutorials here?
Tutorial
A guess would be something like this :
Someone please correct me if Im wrong.Code:#include <iostream>
using namespace std;
void recursion(int arg);
int main()
{
cout << "This is repetition" << endl;
for (int x=0;x < 6; x++)
cout << x << endl;
cout << endl << "This is recursion" << endl;
recursion(5);
system("PAUSE");
}
void recursion(int arg)
{
if (arg > 0)
recursion(arg-1);
cout << arg << endl;
}
Recurrison repeats a chunk of code. Repetition runs different chunks of code that are the same.Quote:
I would like to know the difference between recursion and repetition.
Recurrison = good (when necessary)
Repetition = bad, bad, BAD!
Understand? :D
This is repetition:
Code:cout<<"Hello, world!"<<endl;
cout<<"Hello, world!"<<endl;
cout<<"Hello, world!"<<endl;
cout<<"Hello, world!"<<endl;
cout<<"Hello, world!"<<endl;
cout<<"Hello, world!"<<endl;
Recursion is a great tool when necessary, but should probably be avoided when there is another (reasonable) way to accomplish the same thing. If the recursion goes more than a few levels deep, overhead incurred from calling the function repeatedly can cause problems. In many cases (not all, of course), recursion can be replaced with a while loop.
It's also kind of interesting to write an infinately recurring function like:
Don't worry, it won't crash your comp! You'll notice that after a certain number of calls your program will terminate, this is because you've used up all the mem you're allowed.Code:void func(int x)
{
cout << x << endl;
x++;
func(x);
}
I hope that's right.
What's a few?Quote:
few levels deep
actually you don't use up memory that your program's been allowed.
You overflow the stack (its kind the same but not really)
Every time you call a function it pushes all the vars into the stack and because it calls it self without an end condition the stack gets filled up and then your program exits with a segmentation fault.
See Stack-Overflow or for a REALLY REALLY good example and explanation of how the stack is/works and how to 'use' it...
Aleph1's Smashing the Stack for Fun and Prophit
Also, see pointers and memory in my signature below
-LC