+ 1

How to master recursion in c/c++..

These are 2 different codes: 1st by me and 2nd by GFG. Both calculates the sum of an array but mine is different and maybe poor.... Mine one: #include<stdio.h> int a[5]={1,2,6,8,9}; int main() { int x; x=s(4); printf("sum is %d",x); return 0; } int s(int i) { static sum; if(i==0) { sum=sum+a[i]; //return sum; } else{ sum=sum+a[i]; i--; s(i); } return sum; } By GFG: #include <stdio.h> int findSum(int A[], int N) {     if (N <= 0)         return 0;     return (findSum(A, N - 1) + A[N - 1]); } int main() {     int A[] = { 1, 2, 3, 4, 5 };     int N = sizeof(A) / sizeof(A[0]);     printf("%dn", findSum(A, N));     return 0; } Which one is more appropriate and easier to explain?? Im not sure that does really my code is following recursion or not. Can u explain/guide me?. Give some tips to master recursions also.

20th May 2020, 4:05 PM
Nikhil Sharma
Nikhil Sharma - avatar
2 odpowiedzi
+ 1
When you call s(i) inside the function, what are you trying to achieve? s(i) returns an integer, so you have to assign something to it. When making a recursive function, think of your parameter as a state, then find the relation between each state, and finally, call next state.
21st May 2020, 2:50 PM
Bobby Fischer
Bobby Fischer - avatar
0
But,which type of code?? Im unable to solve the easiest questions on recursions.. What should i do. Mainly in BFS,DFS BST insertion deletion,etc.
20th May 2020, 4:32 PM
Nikhil Sharma
Nikhil Sharma - avatar