Trying to code triangle numbers from 4 ie 4 + 3 + 2 + 1. Why does it not work with the while loop. Appreciate your comments... | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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; }

16th May 2021, 4:32 PM
Grandad
Grandad - avatar
2 Answers
+ 1
The recursion itself is a sort of a loop by itself, so basically you are doing a loop in a loop.
16th May 2021, 4:46 PM
Mihail
Mihail - avatar
- 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--; }
16th May 2021, 4:53 PM
A͢J
A͢J - avatar