how to change from iterative function to recursive function?

Hi i have a problem. I am having a difficultly to change a function to recursive function.

This is my iterative function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
char swap(char charArray[], int col)
{   	
	char temp;
	
	for(int i = 0; i < col; i++)
	{
		for(int n = col; n > i; n--) 	 
		{
			if(!checkvowel(charArray[i]))
			{   
				if(checkvowel(charArray[n]))  
				{	 
					temp = charArray[i];
					charArray[i] = charArray[n];
					charArray[n] = temp;
				}
			
			}
		}	 
	}	
}


while this is my recursive function
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
char swapR(char charArray[], int col,int n, int i)
{   	
	char temp;
	
	if(n > i)
	{	
		if(!checkvowel(charArray[i]))
		{
			if(checkvowel(charArray[n]))
			{	 
				temp = charArray[n];	
				cout << temp << endl;
				charArray[n] = charArray[i];
				charArray[i] = temp;
				
				return swapR(charArray, col ,n--, i++);	   
			}	 	 
		}
		n--;
	}
	else
	{
		i++;
	}
}


I have been trying for quite a while and still unable to get the output..
Any help will be appreciated. Thanks
function call? place a function call where you want to call the recursive function.
i have place the function call and still unable to get the output...
Why??
 
return swapR(charArray, col ,n--, i++);


why is there a return statement?

you want to make a recursion right?

make it void and delete the
return
statement.

like this 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
void swapR(char charArray[], int col,int n, int i)
{   	
	char temp;
	
	if(n > i)
	{	
		if(!checkvowel(charArray[i]))
		{
			if(checkvowel(charArray[n]))
			{	 
				temp = charArray[n];	
				cout << temp << endl;
				charArray[n] = charArray[i];
				charArray[i] = temp;
				
				swapR(charArray, col ,n--, i++);	//swapR only   
			}	 	 
		}
		n--;
	}
	else
	{
		i++;
	}
}
lines 7 - 18 seem to be all right.
the others should be if(n >= 0) rather than if(n > i), and remove lines 19 - 23, n and i are changed on recursive function call.
also, you don't need the int col. you're not using it anywhere.
your function is supposed to return char, but your iterative version doesn't return anything at all. either add something to return or make the function void.
if you decide to make it a void function, delete the 'return' on line 16 and leave a simple function call, because void functions cannot return anything and void cannot be returned.

edit: also, it could be that n-- first passes n to the function and only then decreases it. write either --n or n-1.
Last edited on
Topic archived. No new replies allowed.