Recursive vs Loops

I am trying to convert a recursive function to a loop. However, it is not working. Please advise what I am doing wrong. Thanks in advance!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//recursive function
int function(int x){
	if (x % 3 == 0){
		return 1;
	}
	return 1 + function(x - 2);
}


//recursive function rewritten as loop is not working properly
int function(int x){
	int num = x-2;
	int sum = 0;
		
	for (; num % 3 != 0; num -= 2){

		sum = 1 + num;
		return sum;
	}

	return 1;
}
Last edited on
A loop with an unconditional return in the body is not a loop.
Topic archived. No new replies allowed.