0
Trying to code triangle numbers from 4 ie 4 + 3 + 2 + 1. Why does it not work with the while loop. Appreciate your comments...
#include <iostream> using namespace std; int TriNum(int N); int main() { cout << TriNum(4); return 7; } int TriVar = 0; int TriNum(int N) { while(N >= 1). /* when I replace 'while' with 'if' , the function works well */ { TriVar += N; TriNum(--N); } return TriVar; }
2 odpowiedzi
+ 1
The recursion itself is a sort of a loop by itself, so basically you are doing a loop in a loop.
- 1
Grandad
Just do N-- instead of TriNum(--N) because you are using while loop which behaves like recursion.
And why there is return 7 in main.
This is using recursion:-
if (N >= 1) {
return 1;
} else {
return N + TriNum(N - 1);
}
---------
This is using while loop:
while (N >= 1) {
sum += N;
N--;
}