- 1

Explain me this code

#include <iostream> using namespace std; int sum = 0; int recSum(int n) { //complete the function if (n <= 1) { sum += 1; } else { for (int x = 1; x <= n;) { sum = sum + n; n--; } } } int main() { //getting input int n; cin >> n; //call the recursive function and print returned value recSum(n); cout << sum; return 0; }

29th Jun 2021, 3:57 PM
Abhishek Bairwa
Abhishek Bairwa - avatar
2 Answers
+ 4
First of all the code is not well-written. Since your function aren't returning anything, why don't you use the void instead of using int type? Now, let me explain what does the code does. I believe the code works like that, input:5 output: 5+4+3+2+1=15 If the value of n is less than or equal 1 the value of sum increments 1 and it prints 1.Otherwise if the value of n is greater than 1 it goes to the else statement of that function. Then this line works, for (int x = 1; x <= n;) { sum = sum + n; n--; } I must say this is another bad way of writing code because you can use for (int x = 1; x <= n;n--) instead of adding n-- at the end or you can use x++ and use : sum=sum+x; instead of sum=sum+n; Anyway, the code starts from adding the value of n first and then decrements and adding again and again until n becomes <1; So if you give the input 5, your code will Start adding from 5 then 4 then 3... until the value of n is less than 1 and since the sum is a global variable it can be called from the main function. So the value of sum becomes: 5+4+3+2+1=15
29th Jun 2021, 4:16 PM
The future is now thanks to science
The future is now thanks to science - avatar
0
It's look like, coder was tring combine for loop and recursion. And Its bad idea. He must first decide what method he want to use. a) using for loop: Int sum=0; For (int i = 0; i< n; i++) { Sum += i; } Return sum; B) using recursion: If(n==1) return 1; Else return n+recSum(n-1); But because name of the funkcion is recSum, I thing the gol is practise recursion, whitch mean optiin B.
30th Jun 2021, 6:50 AM
Filip DobeĆĄ