Click here to Skip to main content
15,886,799 members
Articles / Desktop Programming / MFC

How to replace recursive functions using stack and while-loop to avoid the stack-overflow

Rate me:
Please Sign up or sign in to vote.
4.95/5 (83 votes)
1 Jul 2015MIT8 min read 304.6K   2.3K   184  
This article explains 10 rules (steps) for replacing the recursive functions using stack and while-loop to avoid the stack-overflow.
#include <tchar.h>
#include "BinaryRecursion.h"
#include "LinearRecursion.h"
#include "MutualRecursion.h"
#include "NestedRecursion.h"
#include "TailRecursion.h"


int _tmain(int argc,_TCHAR argv[] )
{
	// Binary Recursion
	int result = FibNum(10);
	int result2 = FibNumLoop(10);

	printf("FibNum(10) = %d\n",result);
	printf("FibNumLoop(10) = %d\n",result2);


	// Linear Recursion
	result = Fact(10);
	result2 = FactLoop(10);

	printf("Fact(10) = %d\n",result);
	printf("FactLoop(10) = %d\n",result2);


	// Tail Recursion
	result = FibNum2(10,5,4);
	result2 = FibNum2Loop(10,5,4);

	printf("FibNum2(10,5,4) = %d\n",result);
	printf("FibNumLoop2(10,5,4) = %d\n",result2);


	// Mutual Recursion
	bool bResult = IsOddNumber(10);
	bool bResult2 = IsOddNumberLoop(10);

	bool bResult3 = IsEvenNumber(10);
	bool bResult4 = IsEvenNumberLoop(10);

	printf("IsOddNumber(10) = %d\n",(int)bResult);
	printf("IsOddNumberLoop(10) = %d\n",(int)bResult2);
	printf("IsEvenNumber(10) = %d\n",(int)bResult3);
	printf("IsEvenNumberLoop(10) = %d\n",(int)bResult4);


	// Nested Recursion
	result = Ackermann(3,2);
	result2 = AckermannLoop(3,2);

	printf("Ackermann(3,2) = %d\n",result);
	printf("AckermannLoop(3,2) = %d\n",result2);

	while(1){}
	return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer
United States United States
Woong Gyu La had been working as a software developer for over 8 years.
His personal interests are improving his personal projects,

EpLibrary (Visual C++ Utility Library)
https://github.com/juhgiyo/EpLibrary[^]

EpOraLibrary (Oracle OCI Wrapper Library for Visual C++)
https://github.com/juhgiyo/EpOraLibrary[^]

EpServerEngine (Visual C++ WinSock Server/Client Engine)
https://github.com/juhgiyo/EpServerEngine[^]

And other projects can be found at
https://github.com/juhgiyo?tab=repositories[^]

Finally, my other articles can be found at
http://www.codeproject.com/Articles/juhgiyo#articles[^]

You can contact me at juhgiyo@gmail.com[^]

Comments and Discussions