Public Group

#### Archived

This topic is now archived and is closed to further replies.

# alternative to recursion

This topic is 5715 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

How would you go back to the beginning of a program without using main recusively? [edited by - Magriep on April 17, 2003 9:41:11 PM]

##### Share on other sites
you could just put everything inside main inside a loop of some kind.

if you just want to go back to the beginning once, you could use a for loop:

for (int i = 1; i <= 2; i++)
{
program statements
...
}

there might be a better way to do that, but that would work

##### Share on other sites
that won''t work for me, I need something that would work just like recursion, but without the penalty of a memory hog if it keeps on being called.

##### Share on other sites
Any recursive function can be rewritten as a loop (you might want to Google for this). Often, however, you will need to make a stack and push what in a recursive function would be return values as you iterate.

##### Share on other sites
int main()
{
bah:

//..
//..
//..

goto bah;

return 0;
}

I would just use a loop I don''t understand why you couldn''t design your program into a loop.

##### Share on other sites
i dont think anyones mention do....while loops yet. those work well for what u wanna do.

##### Share on other sites
Miserable is right. Any recursive function can be rewritten as a loop. Sometimes this is very difficult though, which is why recursion is used. Anyway, most times when you convert a recursive function to a loop, you need a stack data structure to keep track of return values and such.

The tradeoff is looking at how much of a memory hog the recursive function is versus how much of a memory hog the stack would be (usually the loop with stack is much much much more efficient), and also how difficult it is to convert from recursive to loop.

If you could give us a more precise idea of what you are trying to do, maybe we could offer more help. The best way to go back to the beginning of any code segment is with a loop.

##### Share on other sites
Ok now I''m going to post my source since it might give you a better idea of what i''m tring to do. I have loops, so i don''t know if I should do what ph33r suggested or if there was a way to get back to the normal loop. The place where I want to have an alternative to recursion is the last function called PlayAgain();. At this moment is calls main recursively and I know it''s a bad thing which is why I''m posting here.

  /************************************************************Program:      Tic-Tac-ToeFile:         Main.cppFunction:     Main (complete program listing in this file)Description:  game of TTTAuthor:       Magriep(mg)Environment:  MS Visual C++ version 6, Windows 98.Revisions:    1.00  3/15/03 (mg) First release              1.10  3/23/03 (mg) Finished user input			  1.15  4/07/03 (mg) Re-did grid appearance			  1.20  4/08/03 (mg) made minor structure changes			  1.30  4/17/03 (mg) Finished checking for wins								 First stable release************************************************************/#include <iostream>#include <stdlib.h>#include <time.h> #include <windows.h>#include <conio.h>// Function prototypesvoid GameMain();bool CheckWin();void Write2Grid(int choice, int player);void ShowGrid();void GetInput(int player);void PlayAgain();// Variable definitions char Grid[3][3] ={''7'',''8'',''9'', // This sets up the tic tac board.''4'',''5'',''6'', // Using a 2d Array.''1'',''2'',''3''};int player;using namespace std;void main() {	while(TRUE) {		system("cls");		cout << "Tic-Tac-Toe v 1.3 BETA" << endl << endl; 		int menu;		cout << "1. Head to Head TTT" << endl			<< "2. About" << endl			<< "3. Quit" << endl << endl			<< "Enter a number: ";		cin >> menu;		switch(menu)	// switch for menu		{		case 1:			GameMain(); // start game			break;		case 2:				// about			system("cls");			cout << "Tic-Tac-Toe v 1.3 BETA" << endl << endl <<				"By: Mike Griepentrog" << endl;			getch();			break;		case 3:		// exit						exit(0);			break;		default: cout << "Not an option!" << endl;		}	}}void GameMain() {	ShowGrid();	int randn;						// randomly selects who goes first	int choice;	srand(time(NULL));	randn = rand()%2;	if(randn == 0) {		ShowGrid();		player = 1;		cout << "Player 1(X) goes first. ";		cin >> choice;		Write2Grid(choice, player);	}	else {		ShowGrid();		player = 2;		cout << "Player 2(O) goes first. ";		cin >> choice;		Write2Grid(choice, player);	}}bool CheckWin() {	for (int j = 0; j < 3; j++) {				// you have a win if they are all equal			if ( (Grid[j][0] == Grid[j][1]) && (Grid[j][1] == Grid[j][2]) ) {			return true;		}		if ( (Grid[0][j] == Grid[1][j]) && (Grid[1][j] == Grid[2][j]) ) {			return true;		}	};			//for diagonal win	if( (Grid[0][0] == Grid[1][1]) && (Grid[1][1] == Grid[2][2]) ) {		return true;	}	if( (Grid[0][2] == Grid[1][1]) && (Grid[1][1] == Grid[2][0]) )	{		return true;	}	else {		return false;	}}void Write2Grid(int choice, int player) {	// writes info to board & checks to see if taken	if ( choice < 1 || choice > 9) {		cout << "Select a number that''s on the board." << endl;		getch();		GetInput(player);	}	char xo;								// requests input again when done	xo = (player == 1) ? ''X'' : ''O'';	int c = 2 - (choice-1)/3;	int d = (choice-1)%3;	if ( (Grid[c][d] == ''X'') || (Grid[c][d] == ''O'') ) {		cout << "Spot has already been taken! Select another spot." << endl;		getch();		GetInput(player);	}	else {		Grid[c][d] = xo;		if (CheckWin() == true) {			system("cls");			ShowGrid();			cout << "Congradulations, "<< xo << " has won!" << endl;			getch();			PlayAgain();		}		else {			player = (player == 1) ? 2 : 1;			GetInput(player);		}	}}void GetInput(int player) {  // gets input and calls function to write to board	int choice;	while(TRUE) {		switch(player) {			// switch to change players each turn		case 1:			ShowGrid();			cout << "It''s X''s turn. " << endl;			cin >> choice;			Write2Grid(choice, player);			break;		case 2:			ShowGrid();			cout << "It''s O''s turn. " << endl;			cin >> choice;			Write2Grid(choice, player);			break;		default:			cout << "Error! Program will now terminate.";			getch();			exit(0);			break;		}	}}void ShowGrid() {			// draws out the board and requests input	system("cls");								// if first time flag to send to GetInput to rand.	cout << " " << Grid[0][0] << " | " << Grid[0][1] << " | " << Grid[0][2] << endl		<< "-----------" << endl		<< " " << Grid[1][0] << " | " << Grid[1][1] << " | " << Grid[1][2] << endl		<< "-----------" << endl		<< " " << Grid[2][0] << " | " << Grid[2][1] << " | " << Grid[2][2] << " " << endl << endl; }void PlayAgain() {	char again;	system("cls");	cout << "Play again? Y/N ";	cin >> again;	again = toupper(again);	while(again != ''Y'' && again != ''N'') {		system("cls");		cout << "That isn''t Y or N! Try again." << endl;		cout << "Play again? Y/N ";		cin >> again;		again = toupper(again);	}	if(again == ''Y'') {		main();	}	else {		exit(0);	}}

##### Share on other sites
i tried to fix it for you but i could not get it to copy correctly, so for the sub playagain() make it return either a bool or an integer, if the player wants to play again, then it will return true, then make Write2Grid return this value (true or false) to the gamemain() then if it comes true to game main, you can either return and it will go back to your very first menu, or put your gamemain() statements in a while(1) loop, if (Write2GRid() = false) return; so that if they dont'' wanna play again it goes back to the main menu, else it loops through the gamemain again, you need to make a better game loop, put all your function calls in it, isntead of randomly through out other functions, this would make this task alot easier...

##### Share on other sites
so say I put a do while loop in GameMain, before the loop i'll have what's in there now, if it goes back to the loop will it start over (choose who goes first again)?

[edited by - Magriep on April 18, 2003 1:11:07 PM]

1. 1
2. 2
3. 3
Rutin
15
4. 4
khawk
13
5. 5
frob
12

• 9
• 9
• 11
• 11
• 23
• ### Forum Statistics

• Total Topics
633669
• Total Posts
3013259
×