Click here to Skip to main content
15,900,973 members
Everything / Recursion

Recursion

recursion

Great Reads

by MehreenTahir
This article will show you an alternative way of using C++; How to write functional code in C++. You’ll see how to write more concise, safer, readable, reasonable code.
by HoshiKata
Practical on the fly fast mesh generation from arbitrary points.
by Anton Chibisov
This tutorial showcases how to implement C++ delegates which are capable of being bound to methods and functions having arbitrary signature, i.e., any number and type of parameters and return value.
by Eric Z (Jing)
Evaluation order matters!

Latest Articles

by Han Bo Sun
This tutorial will show you how to load and display hierarchical structured comments using RESTFul service and JavaScript.
by MehreenTahir
This article will show you an alternative way of using C++; How to write functional code in C++. You’ll see how to write more concise, safer, readable, reasonable code.
by Mojtaba Hosseini
A graphical binary tree. Features: add, remove, or search for a node. Recursive algorithm has been used
by Rahul_Biswas
A simple explanation of the recursive CTE concept of T-SQL

All Articles

Sort by Title

Recursion 

4 Nov 2017 by Member 13502303
The programm should take the (final) number x and calculate the square root of it. It shall stop after n iterations. Furthermore it shall be solved with recursion. My code so far: public class Babylon{ double sqrt( final double x, final int n ) { double s; if ( n == 0...
4 Nov 2017 by Patrice T
I don't know what you try to do, but: x/x is 1, and (x+x/x) is x+1 Guessing you want to use the Babylonian method, you need to keep track of the square root you search and its current estimate. Methods of computing square roots - Wikipedia[^] There is a tool that allow you to see what your code...
4 Nov 2017 by Kenneth Haugland
You need to do something like this: double sqrt(double S, double x, double n) { if (n == 0) return x; else return sqrt(S,0.5*(x+S/x), n - 1); } S will never change since its the number you want...
13 Mar 2013 by Michael D Bray
Filling in text templates from a data source.
20 Jan 2021 by Emre Yaşar
#include int summation(int N); int summation(int N) { if (N != 0) return N + summation(N - 1); else return N; } int main(){ int N; printf("\n Enter a positive number: "); scanf("%d", &N); ...
20 Jan 2021 by Christian Graus
your seqence is binary. 2^0, 2^1, 2^2, etc. So you can do what by passing in the powers and doing 2 the power of x in your code
20 Jan 2021 by Emre Yaşar
#include using namespace std; // function to calculate sum of series int calculateSum(int n) { // initialize sum as 0 int sum = 0; // loop to calculate sum of series for (int i = 0; i
12 Aug 2021 by Hemil Shah 2021
As the PrintPattern function is only being called twice, it prints just 2 exclamation marks '!' instead of 3. Its not a very difficult problem but I am stuck at it. Please help ASAP. What I have tried: #include char PrintPattern(int...
12 Aug 2021 by KarstenK
Use the debugger to find out how often your function is called. I bet 3 times :-O
12 Aug 2021 by Patrice T
Try char PrintPattern(int n) // function should be void instead of char. { if(n>0) { printf("*"); n--; PrintPattern(n); printf("!"); } if(n!=0) printf("!"); } As KarstenK suggested, try...
18 Aug 2011 by Herre Kuijpers
A utility that allows you to enter simple and more complex mathematical formulas which will be evaluated and calculated on the spot
9 Aug 2013 by Redslide
Modify MVC Routing to allow routes such as /Electronics/Software/Operating-Systems/PC/Windows-8-Installer
16 Feb 2015 by Eric Z (Jing)
Evaluation order matters!
7 Jan 2019 by kavinderrana121
I was trying to solve the question on basic recursion using memoization https://www.spoj.com/problems/COINS/ NOTE-> max value of n is 1 000 000 0000 I definitely must add memoization to solve this problem But when i am declaring array of size `1 000 000 000` compiler is saying std::bad_alloc ...
8 Jan 2019 by Patrice T
Quote: But when i am declaring array of size `1 000 000 000` compiler is saying std::bad_alloc Your problem is that you did not analyze the problem, you are jumping strait to the second most simple minded solution which replaced the brute force solution by another brute force solution, in...
11 Sep 2011 by brunofer2007
Easy way to sort nodes in a TreeView using a recursive function.
28 Jun 2011 by rytucker
Using SQL server 2008I need a recursive join to output records on the right side once for every day. Records on the left define the date, and are joined with the right by a range of matches.Basically I'm trying to generate schedule recommendations based on resources who have availability...
28 Oct 2010 by SuperAdministrator
Hello,I am trying to automatically build a tree view by giving it the following values.number of levels :Nlevelsnumber of children in each level: NchildrenAtEachLevelIs this doable?Any help would be highly appreciated.
28 Oct 2010 by Pawan Kiran
Equal No of Childs For Each Parent NodePrivate Void FillTreeView(Treeview Tv,int NoofParents,int NoofChilds){ for(int i=0;i
28 Oct 2010 by qontary
Try this. I modify the code posted by Mr. Pawan Kiran.private void FillTreeView(TreeView Tv, int NoOfLevels, int NoOfChildsOfEachLevel) { if (NoOfLevels
23 Apr 2011 by algrn912005
Hi,I'm having a little trouble with creating a function to find the average depth of a binary search tree. The definition of average depth of a tree is the sum of the depth of all nodes divided by the total number of nodes. The definition of the depth of a node is the distance from the root of...
23 Apr 2011 by Sergey Alexandrovich Kryukov
The problem is not finding the depth, the problem is to do it just once. Here is the way to do it: do not create a function for finding a depth of the current node. Instead, include the depth of a current node as a parameter of the recursive function.void AccumulateNodeInfo( node *...
24 Apr 2011 by mbue
For every thing i do with trees i use walk functions.Example for a walk function:class INode{public: INode* _child; INode* _next;};class IWalk{public: // IWalk virtual HRESULT Enter(INode* pNode) = 0; virtual HRESULT Leave(INode* pNode) = 0;};void...
2 Dec 2016 by Member 12884199
You have to find average depth at once .I use this formula->AD(n)=ln(n+1)÷ln2This you can find from the formula as we can find maximum no.of nodes by //n=(2^d)-1Where d is depth of the tree.
3 Jun 2011 by Cyborgx37
A simple F# application that solves Sudoku puzzles. Links to helpful resources are also provided.
15 Nov 2018 by average_angela
for a given number 'n' we put numbers form 1 to n around a table and start deleting the numbers starting from 2 like this: ============EXAMPLE=========== n=6 1 2 3 4 5 6 --> we delete 2,4,6 now we have: 1 _ 3 _ 5 _ then if we imagine them around a table after 6 we gotta delete 2 but since it...
15 Nov 2018 by CHill60
We do not do your homework for you. Exercises like homework are set to cement the knowledge from the course into your brain, to help you practice the new skills and to let your tutor know where you need extra help. Give it a go. It is not as hard as you think. Then, if you are still stuck, come...
15 Nov 2018 by OriginalGriff
We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action. Get some paper and a pencil, and...
15 Nov 2018 by KarstenK
You need to visit some Learn C tutorial to learn the basics. You must learn about arrays, malloc and free. You must implement some recursive function which does the job. It could be with the prototype int* shortenArray(const int *array, int cnt);
23 Jun 2011 by Mesrop Simonian
Hi everyone,I have a hierarchical tree that can have an unspecified number of branches. You add children to parents then parents to their parents and so on. Everything then gets added onto the main branch. Something like this:MyTree t = new MyTree(); Branch topBranch = new...
22 Jun 2011 by OriginalGriff
It's pretty simple: the runningTotal is passed to the routine by value, not buy reference. So when you make changes to it, they are not reflected back up the tree.For example:void Change (int i) { Console.WriteLine(i); if (i
23 Jun 2011 by TRK3
See my reply in Solution 1 for why root level siblings are not getting traversed.I think a better way to do this, would be to have a member variable called TotalNumberOfChildren.When you create a branch, TotalNumberOfChildren is set to zero.Add a member function:void...
24 Jun 2011 by BobJanova
I think this is easiest in two passes (which has been alluded to in previous answers), a precalculation pass where the totals for each node are recorded (which must traverse the whole tree), and a calculation pass where the branch's value is compared to the parent or root.class Branch {...
27 Sep 2010 by borgasia
I have a list array.Now i need to go through this array and fill in positions,depending on the level.Each level will start at position 10, increasements are 10.The array is sorted at Level. This may not be changed.I heared something about recursive loops, but i am not familiar with...
26 Sep 2010 by DaveAuld
A recursive loop is just a function that calls itself. No need to use one here.One method of performing this is to use a some form of HashMap (a collection) where the level is the key and the last used position is the value for the associated level.Step through the array, check the...
26 Sep 2010 by Abhishek Sur
Recursion is useful when you have a hierarchy of data. May be a Tree Traversal or fetching data from parent-child relation. In your case it is very straight forward, so I recommend not to go for recursion, rather use normal loop to do this.If you want to know about Recursion you can go...
29 Sep 2010 by borgasia
I found a normal loop to do so!private void setPos() { recBom Bom; int position = 0; for (int level = 1; level
18 Sep 2020 by Member 14868207
I'm trying to use ArgumentManager.h to read the input and output file, but still some problems here, my code cannot successfully read the file and use reverse the Linked List. Anyone can figure out which part is wrong and help me correct it? I...
18 Sep 2020 by Patrice T
Quote: my code cannot successfully read the file and use reverse the Linked List. As far as I can see your code reads input file and do nothing with it. while(fin) { string line; getline(fin, line); } Your code do not behave the...
14 Jul 2020 by Pranshu Kashyap
Link to The Problem: https://codeforces.com/problemset/problem/166/E[^] Problem Statement: *You are given a tetrahedron. Let's mark its vertices with letters A, B, C, and D correspondingly. An ant is standing in the vertex D of the...
14 Jul 2020 by OriginalGriff
We are more than willing to help those that are stuck: but that doesn't mean that we are here to do it all for you! The idea of these challenges is to test your knowledge; your abilities. To give you a chance to change the way you think about...
14 Jul 2020 by Patrice T
Quote: I didn't knew that this site is to tell you that if you are stuck at any problem then tell your doubts to your mentor and they will simply say solve yourself we are here just for posting nonsense answers. In this site, we help you to fix...
27 Apr 2014 by EbolaHost
say we have this function :Function ov(byval a as integer) Return ov(a)End functionAs far as I know the program will crash because it will keep storing the 'a' variable in memory as a different variable each timeBut can this :Function ov(byref a as integer)a=0 Return...
27 Apr 2014 by DamithSL
For a recursive function to stop calling itself we require some type of stopping condition.both types of your recursive methods will hang because of no Stop condition
27 Apr 2014 by Dave Kreskowiak
It will crash eventually.Why? Because when you call a function a return address is pushed onto the stack so the processor can know where to return to. Constantly pushing a return address onto the stack will eventually exhaust it, causing a StackOverflowException.
26 Feb 2012 by Samuel Gonzalo
24 May 2011 by Sandeep Mewara
oh ___ hell .you don't need me to give lecture on what you are talking about. i dont have time for it.. need help thats why i posted it here its 3.30am here and at 7 i have to present it:doh: Great attitude. You fail to complete your work in time.You come here for help and when someone...
12 Nov 2013 by Jobless Creature
CTE To find all the related nodes in a hierarcy
10 Oct 2014 by Wael Tayara
Well, this is giving me a real headache. I'm building a matrix determinant function to compute NxN determinant, and I'm using recursion. The logic is working right but I'm not able to get the final value computed correctly.Here is my code for Matrix Determinant: public static double...
10 Oct 2014 by Wael Tayara
This is the part where should be modified :)for (int j = 0; j
14 Dec 2019 by Member 14689791
Saruss' Rule can be useful for faster & memory efficient computation of Determinant. because it is non recursive. You can get application on https://github.com/apanasara/Faster_nxn_Determinant
30 Sep 2012 by frubsen
I'm trying to make a program where you specify a root directory and it will recursively search for all .mp4 files from that folder on.My problem is that once it finds a folder it does not have access to, it just stops searching and doesn't display all the results.My code is as...
30 Sep 2012 by Sandeep Mewara
My problem is that once it finds a folder it does not have access to, it just stops searching and doesn't display all the results.So? The solution is not in the codes. You need to make sure that the folders have the access permission set such that you can browse through it. Until unless,...
30 Sep 2012 by Sergey Alexandrovich Kryukov
Unfortunately, this is one of the rare cases where you need to make a fine-grain try-catch block and block the propagation if exception (but not re-throwing). In this approach, you need to put your try-catch in the minimal context containing the line with the operation with each file system...
3 Feb 2013 by Normz Antonino
This tip shows you how to convert numbers to words neatly.
3 Jul 2013 by mostafa_bioinfo
please i need to convert the following code to iterative instead of recursive. this code solve the partial digest problem in dna.def Place(L, X): if L==[]: X1 = copy.deepcopy(X) X1.sort() print X1 return True width = max(X) if debug: ...
27 Mar 2011 by Adrian Vintu
Deep copy routine for complex objects that can return a destination type different than the source type.
28 Oct 2018 by Member 14035676
We get non negative integer number n from user and we must print all subsets of set ({1,2,3,...,n}). for example for n=3 we must print: {1 , 2 , 3} {1 , 2} {1 , 3} {1} {2 , 3} {2} {3} {} ,s are optional and the sequence can be printed without any comma. (like {1 2 3}) I must add that the...
28 Oct 2018 by OriginalGriff
We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action. The whole idea is to get you to...
28 Oct 2018 by KarstenK
You must write code for a function which is outputing the actual data and than recursive call that function for all subsets in which one item is removed. But how are you allowed to store that input? If in doubt ask your teacher!!!
28 Oct 2018 by Patrice T
Quote: I see a lot of codes in the Internet that solve this problem with arrays or using a bit array that indicate whether we use a number or not. The issue is that in this question, we are not allowed to use -any- type of array or other data structures like vector ,etc. Since any variable is...
4 Mar 2013 by Caleb McElrath
How-To: Create a JavaScript object during runtime based on an XML file.
12 Mar 2010 by JasonDove
I hate sub reports and always consider them the last resort in any reporting solution. The negative effect on performance and maintainability is just not worth the easy ride they give the report writer. Nine times out of ten reporting requirements can be met using a little forethought and...
12 Nov 2012 by HoshiKata
Practical on the fly fast mesh generation from arbitrary points.
13 Nov 2010 by PSU Steve
You can just use "not IsDisable" versus the IF...ELSE block. Additionally, the recursive call to ControlStatus should be done all the time so that the parent control is enabled/disabled along with the children. // to enable\disable the control & its child controls public...
13 Nov 2010 by jarvisa
public void ControlStatus(Control control, bool isDisable){ foreach (Control c in control.Controls) if (c.HasControls()) ControlStatus(c, isDisable); else { WebControl wc = c as WebControl; if (wc != null) ...
13 Nov 2010 by a_pess
Alternative For VB.NET Windows Forms Private Sub ControlEnabled(ByVal ctrl As Control, ByVal isDisable As Boolean) Me.ControlEnabled(ctrl, isDisable, True) End Sub Private Sub ControlEnabled(ByVal ctrl As Control, ByVal isDisable As Boolean, ByVal allowRecurse As...
31 Dec 2009 by dexit2k
Hi Guys!Thx for reding!My Situation:i use VB.NET 3.5, VS2008i have got an tree of data. i got the data via an app api call.about: 300MB, 1100 Nodes. max tree deep of 6my single thread func:Private Function IterateThruTree(ByVal AktComponet As Component, ByVal AktDeep As...
31 Dec 2009 by AspDotNetDev
Well, you could store a count of threads at the class level. Whenever a new thread is created, add to the count. When the thread is complete, remove from the count. When the maximum count is reached, wait for it to be reduced before starting a new thread. You would likely do this check to make...
1 Jan 2010 by dexit2k
aspdotnetdev wrote:So, if the threads are at max, then just recursively call IterateThruTree. But if the threads are less than max, then call IterateThruTree as a new thread.Thats an realy good idea, thx.
1 Jan 2010 by N a v a n e e t h
wrote:i wonne do this in threads.I will not recommend to use multi threading just to iterate over the tree. It will make the code complex and it is very tough to maintain the order of iteration. Do the iteration on single thread and spawn new threads for processing.
1 Jan 2010 by dexit2k
wrote:I will not recommend to use multi threading just to iterate over the tree. It will make the code complex and it is very tough to maintain the order of iteration. Do the iteration on single thread and spawn new threads for processing.its the iteration what costs the cpu time, not...
5 Jul 2013 by Askar Imran
Well in our project we are having a requirement as to create a global class file, In each of our ASPX.cs page we have to pass the page controls (Page.Controls) to the global class file i mentioned above, and i need to disable or enable the controls in the class. This can be simply done in each...
27 Mar 2021 by iE7TRAF702
How do I print the Scanner the output of the functions above, and I am a beginner in Java What I have tried: import java.util.Scanner; public class factorial { // Factorial number Non Recursive Use a for...
27 Mar 2021 by OriginalGriff
Look at your main method: You read the number to calculate the factorial of before you prompt the user to enter it! Then printing your answers is simple - you just have to call the method you wrote and print the result. If you define a method...
6 Jul 2019 by Member 14517556
The question is to print a fibonacci series using recursion. I am not getting output for the following code (I use pyCharm for running codes). What I have tried: def fibo(n): if n==0 or n==1: return 1 else: return fibo(n-2)+fibo(n-1) fibo(6)
6 Jul 2019 by Thomas Daniels
The value is being calculated, but you are not doing anything with it - it's just getting discarded. You might want to print it on the console: print(fibo(6))
5 Feb 2012 by C Yang
Program to inventory directories and tally files.
31 Aug 2012 by atamata
File renaming algorith to mimic Windows copy+paste renaming
4 Oct 2011 by imrankasuri
Hi All, i am currently facing an issue and hope that someone will help me.here is the scenario.I have a simple table.Member Table================Member_id Name Opening_Balance Balance_Type1 David 5000 DebitTransaction...
4 Oct 2011 by André Kraak
Have a look at this article Calculating Running Totals[^] and see if you can use it to get your running total working.
22 Nov 2014 by Member 11238028
I'm doing an exercise which reads as follows:Create a function that given a number n the average of the steps they have to make the numbers from 1 to n to get to number 1, for example:1 => 0 steps to get to 12 => 1 steps to get to 13 => 7 steps to get to 14 => 2 steps to get to...
22 Nov 2014 by Philippe Mori
I think that the problem is that you do the division at each step. You need to do the division only once at end.Thus averageCollatz would be renamed sumCollatz and last line would be:return total;Then you would have:double averageCollatz(unsigned int num){ unsigned steps =...
22 Nov 2014 by Andreas Gieriet
The average is the averagea = 1/m ∙ ∑k=0mxkAs a series, you can define the following:1) a0 = x02) an+1 = (an ∙ (n + 1) + xn+1) / (n + 2)This has the problem of the initial average function: the sum may go beyond the number limit, i.e. the term an ∙ (n + 1) is identical with the...
25 Apr 2019 by Michelle Anne Rigor
I am currently creating a Organizational Chart and I need a total count of all the nodes under a certain employee. I researched that I need to use recursive SQL. But it seems to not be working in my query. Instead I repeatedly (I know this seems wrong) put the query in a temp table and add the...
25 Apr 2019 by User 11060979
In case you can use CTE, then based on this: sql server - Counting number of children in hierarchical SQL data - Stack Overflow[^] The SQL lokks like ;WITH ChildrenCTE AS ( SELECT RootID = ID, ID FROM Tbl1 UNION ALL SELECT cte.RootID, d.ID FROM ChildrenCTE cte ...
5 Apr 2018 by Member 13764324
For example: {11, 5, 7, 9, 11, 3, 5} has a total of 2 pairs: 1 pair of 11 and 1 pair of 5 {11, 5, 7, 9, 11, 11} has a total of 1 pair: a pair of 11 {11, 5, 7, 9, 11, 3, 11, 5, 11} has a total 3 pairs: 2 pairs of 11 and 1 pair of 5 Write a recursive function findpair. This function takes 3...
5 Apr 2018 by Jochen Arndt
This is a homework / assignment question. So you will not get a complete solution here. But I have two tips: 1. A recursive function will not "see" the local variables of the caller. If you have to sum up a value, you have to use the return value: int rec_func(some_param) { int result = 0;...
5 Apr 2018 by OriginalGriff
Think about how you would do it manually. I'd start with the first element in the array, and then search for it's match. If I found it, I'd remove the second one from the array. If I didn't, I'd remove the element from the array. Then search again from the next element, if any. At the end, the...
5 Apr 2018 by Patrice T
Your code is nicely recursive, but wrong in many ways. All pairs found in recursion are getting lost: int findpair(int array[], int start, int end) { int pairs = 0; if(end
25 Nov 2011 by Kabwla.Phone
Ha! I get it....I am actually using an adaptation of this technique in production code.But the adapted code required a dept-first search and this original pattern is width-first.Which brings us these new and improved versions:public static List FindControlsWidthFirst( Control...
8 Nov 2011 by Kabwla.Phone
Implemented with a queue and some newfangled yields.Since a queue does not have an 'EnqueueRange', we will still have to do a loop. Of course, enqueue range would be a nice extension method.Excusing the overhead created by the yield, this might use less memory if there are many controls. (Or...
7 Jun 2018 by Stavros Avramidis (asder)
I am making a directed Graph class. I want find if there is any Euler Cycle and update a vector with it's path accordingly. My Function some times work but others add two times the last edge of the path.So i guess it needs to be tydied up. (If others parts of my code are too simple, so I didn't...
7 Jun 2012 by AndyUk06
A recursive algorithm to find all paths between communicating network nodes.
15 Sep 2016 by discompsys
This tutorial describes how to convert the recursive method call in said algorithm into a flat loop call, to save memory in restricted environments.
23 Nov 2018 by MehreenTahir
This article will show you an alternative way of using C++; How to write functional code in C++. You’ll see how to write more concise, safer, readable, reasonable code.
29 Oct 2015 by Sam Dean
void binary(int n){ if(n
29 Oct 2015 by Sergey Alexandrovich Kryukov
Please see my comment to the question.I basically answered you about stack; will also add this: a function parameters are put on the stack, and they disappear with the frame when function returns. But of course, you need to learn seriously how stack, stack frames and calls work, this is one...