Infinite Recursive call

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ThEoNeAnDOnLy
    New Member
    • Aug 2008
    • 2

    Infinite Recursive call

    I recently had an issue with my recursive project in class. Here is the code.

    Code:
    // Recursion.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    #include <conio.h>
    #include <iostream>
    using namespace std;
    
    //define recursive function to get values and store in array
    void getInts(int myArrayParam[], int indexParam)
    {
    	//recursive call
    	if (indexParam<=2)
    	{
    		cout<<"Please enter whole number number "<<indexParam+1<<":";
    		cin>>myArrayParam[indexParam];
    		indexParam++;
    		getInts(myArrayParam, indexParam;
    	}
    }
    
    //define recursive function to ouput values in array
    void displayInts(int myArrayParam2[],int indexParam2)
    {
    	if(indexParam2<=2)
    	{
    		cout<<"Whole number number "<<indexParam2+1<<" is "<<myArrayParam2(indexParam2)<<"."<<endl;
    		indexParam2--;
    		displayInts(myArrayParam2, indexParam2);
    	}
    }
    
    int main()
    {
    	//declare a three element int array and a variable to increment/decrement
    	int myArray[3];
    	int index;
    
    	//call recursive function to get values and store in array
    	getInts(myArray, index);
    
    	//set index to largest element
    	index = 2;
    
    	//call recursive function to output values in array
    	displayInts(myArray, index);
    
    	cout<<endl<<endl<<endl;
    	cout<<"Press any key to exit ";
    	getch()
    	return 0;
    }
    Somehow it will not end the recursion making it infinite. How to I end this madness.
    Last edited by Banfa; Aug 1 '08, 02:45 PM. Reason: Addeed [code]...[/code] tags round the code
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    You don't initialise index before calling getInts.

    In displayInts your end coondition is wrong if indexParam2 <= 2 at the first call then it will be <= 2 for a very long time, seeming infinite.

    And finally you don't have this problem with this code since the posted code does not compile.

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      Originally posted by Banfa
      And finally you don't have this problem with this code since the posted code does not compile.
      I like that conclusion ;-)

      kind regards,

      Jos

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        And the indexParam goes up instead of down.

        Comment

        • ThEoNeAnDOnLy
          New Member
          • Aug 2008
          • 2

          #5
          I C. I'll figure it out. .

          Comment

          Working...