Click here to Skip to main content
15,891,529 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 Score

Recursion 

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.
12 Nov 2012 by HoshiKata
Practical on the fly fast mesh generation from arbitrary points.
13 Apr 2015 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.
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...
16 Feb 2015 by Eric Z (Jing)
Evaluation order matters!
11 Sep 2011 by brunofer2007
Easy way to sort nodes in a TreeView using a recursive function.
27 Jan 2015 by Andreas Gieriet
You may make the example a bit more challenging by employing Divide and conquer algorithms[^].E.g. calculate the sum by calculating the sum of the left "half" plus the sum of the right "half" of your array.int sum(int a[], int size){ int result = 0; if (size == 1) { result =...
19 May 2016 by Matt T Heffron
Recursion is rarely the better choice compared with iteration.It might be more understandable in cases of some problems dealing with recursively defined data structures (that are known to be bounded size!).However there are some problems that would be insanely difficult to represent as...
11 Aug 2016 by OriginalGriff
Development comes in four parts: Design, Code, Test, and Debug.You've done the first three, and now it's time for the fun one: Debugging.Why doesn't it work? I don't know, because you haven't told me how you know it doesn't - you haven't told me what you did in order to test it, or what...
7 Jun 2011 by Ciumac Sergiu
Hi,stack overflow happens when your computer's stack gets too many function calls, thus strings over 150 chars generate such error. There are several workarounds that you can use in order to solve this problem:1) optimize your code to get fewer function calls2) use Stack object in order to...
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...
19 May 2016 by CPallini
The oldie-goldie Wirth's book[^] provides excellent insight on this very argument.
25 Jun 2022 by steveb
I think you're doing this the hard way. Here is an easier way: std::vector v1 = {1, 2, 3}; std::vector v2 = {4, 5, 6}; std::vector dst; std::merge(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(dst));
19 Nov 2009 by Anish M
CREATE PROC GetChildNodes (@ID uniqueidentifier)ASBEGINWITH PermissionList (PermissionID, PermissionName, Level)AS(SELECT ap.PermissionID, ap.PermissionName, 0 AS LevelFROM Permission AS apWHERE PermissionID = @IDUNION ALLSELECT ap.PermissionID, ap.PermissionName, Level + 1FROM
1 Nov 2010 by OriginalGriff
Are you absolutely sure?Even if each element of your 7 dimensional array is a single byte, you will need 100 * 50 * 25 * 25 * 50 * 25 * 25 bytes to store it.97,656,250,000 bytes.97GB of RAM, if it is 1 byte per element.I think you need to rethink your project, just a bit!
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) ...
31 Aug 2013 by OriginalGriff
Yes - but the simplest thing to do is try it. Write a simple C function, and call it with your values. See what it does, by following the code execution in the debugger.To answer your supplementary question, "No" - it will not loop forever if you pass it a negative value, because the...
19 Sep 2013 by nv3
As Jochen already mentioned you forgot to put comment characters in front of some of you comment lines.The error in line 28 result from declaring the pointer ptrToPass after an executable statement. Remember, in C all declarations must be at the top of a function!In your numOfSkips...
8 Jul 2014 by OriginalGriff
It's not easy to explain, particularly when I can't see you eyes, and when they start to glaze over...So I won't try.Instead, let's talk about what recursion is.Recursion is the process of using the same code to work out the various parts of a calculation, and is often demonstrated with...
22 Nov 2015 by Patrice T
Obviously, your own code is like a blackbox to you. It don't do what you expect.What follow is not directly a solution to your problem, but a key that will help you to understand by yourself what is wrong.The debugger is your friend. It will show you what your code is really doing.Follow...
16 May 2016 by CPallini
Iterative, C++ versionvoid find_and_replace( string & text, const string & word1, const string & word2){ size_t pos = string::npos; size_t len = word1.length(); while ( (pos = text.rfind(word1, pos)) != string::npos ) text.replace( pos, len, word2);}
19 Jul 2018 by Eric Lynch
The following should work: private static TreeNode FindFirstVisible(TreeNodeCollection nodes) { foreach (TreeNode node in nodes) { if (node.IsVisible) return node; TreeNode first = FindFirstVisible(node.Nodes); if (first != null) return first; } return null; }...
13 Jun 2019 by Patrice T
Quote: I understand that in the initial step till the base case it assigns 0 to all members of the array, but I don't understand what happens after that. Did you missed that it is a recursive function ? Launch the debugger and watch the code perform, it certainly will help to understand. Your...
1 Jul 2019 by CPallini
As starting point, try #include #include using namespace std; using Matrix = vector >; int maxsum( const Matrix & m, size_t r, size_t c) { if ( c == m[r].size()-1) return m[r][c]; int contrib = maxsum( m,r, c+1); //same row contribution if ( r ==...
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))
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...
25 Jun 2022 by Greg Utas
Maybe someone will help with this. But if they do, you won't have to learn how to use a debugger, which is the only reasonable way to find problems in non-trivial code. A debugger lets you step through your code line by line as it executes, so...
7 Sep 2010 by John Adams
Magnus, I really like the idea! I believe your original idea (posted @ http://www.codeproject.com/KB/linq/LinqToTree.aspx) is even better for the general case - probably better than the solution in the article - it does feel more generic while still being very easy to use.I'm sure you may...
13 Sep 2010 by AspDotNetDev
It's obvious that you're using a bunch of memory and you're doing a lot of processing.ListBox1.Items.Add(CurrentFile)With that line, you are saving a file info object for every file in the path specified, and you are adding it to a listbox. That could consume a lot of memory. Also, you may...
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...
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 *...
18 May 2011 by Programm3r
Hi new guy,Please have a look at the following post: Building a Database Driven Hierarchical Menu using ASP.NET 2.0[^]Kind regards,
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
21 Jun 2013 by Rajesh Anuhya
Here is the direct example for self joinhttp://www.aspdotnet-suresh.com/2012/07/self-join-query-in-sql-server-self-join.html[^]Thanks--RA
1 Sep 2013 by Stefan_Lang
Probably 9 is right. But the question is not:1. The first line of the code is not C code - I assume it's part of the textual description or just defines the input.2. You did not (formally) provide the definition of function f - I assume the last 4 lines of the code describe it. (and I'll...
11 Sep 2013 by Sergey Alexandrovich Kryukov
Please see the comments to the question.Please see:http://en.wikipedia.org/wiki/Recursion[^],http://en.wikipedia.org/wiki/Recursion_%28computer_science%29[^],http://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29[^] (this is not what is used in recursion, but good to know,...
27 Nov 2013 by Snehasish_Nandy
Check thisRecursion in T–SQL[^]
4 Feb 2014 by CoderPanda
First of all, thanks for asking an intellectual question. Don't get to see these often and I, personally, absolutely love to talk about these. I would like you to understand it yourself and I am sure you can. I will only explain the code a bit more to help you out.(Assuming you know what a...
4 Feb 2014 by Mattias Högström
Yes. Recursion can simplify a solution quite a lot.But reading it may be problematic.You are trying to understand 2 problems at the same time.1. How the recursion works.The easiest form of recursion is calling the same function from just one place in the code.Like calculating the...
12 Nov 2015 by Veselin Tenev
Provides simplistic solution to a recursive MySQL table
27 Nov 2015 by mbue
cur->prev = p; if(cur->prev != NULL) it is strongly recommended to use human readable names - so you can see 'cur' is 'p' now. if(p->prev != NULL) p->prev->next = p;regards.
7 May 2016 by Patrice T
Bug report: On first look I would say that your program fail to find the first prime.Question: why do you want to use recursion to find if a number is prime ?Ok it may simplify the code, but it is at expense of PC resources, for large numbers you are at rick of stack overflow.If you...
11 Jun 2016 by OriginalGriff
To do it recursively in the "Class method" is the same as to do it in the non-class method - all you have to do is pass the node to print in:void revPrint(node* pn) { if (pn != NULL) { revPrint(pn->next); count data
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.
5 Jun 2017 by Patrice T
Quote: My function does not work This is not informative. An example of function calling woukd be also helpful. There is numerous problems in your code: binsearch(arr, low, size/2, p); binsearch(arr+mid, mid+1, size/2, p); Depending on the size of arr being odd or even, your code fails on...
6 Jun 2017 by Klaus-Werner Konrad
You don't RETURN a pointer from your recursive binsearch() calls ...
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...
12 Feb 2018 by OriginalGriff
There is no recursion in that code, nor is there a loop. There may be recursion or iteration within the CZKEM class, but we can't see it if there is. You do understand that recursion is calling a method (directly or indirectly) from itself, don't you? public int factorial(int x) { if (x...
15 Apr 2018 by OriginalGriff
It's pretty clear if you just read it. Quote: Write a function plot that will plot the values calculated by another function with rows of asterisks, each asterisk corresponding to the value 0.1. So 1 will be shown with a line of 10 asterisks, 0.5 with a row of 5 asterisks, 2 with a row of 20...
16 Apr 2018 by Patrice T
Not a solution, just advices. Quote: I've been pulling my hair trying to understand this teacher's horrible directions. There is nothing horrible in this requirement, just may be a little more complicated than usual. In fact this requirement is nowhere as complicated as real life requirements....
15 Aug 2018 by OriginalGriff
Recursion is simple to understand: see "recursion" and it'll all be clear! Your function calls itself with different parameters, and return to itself with the value each time when it's calculated. Look at what happens with your code when you pass specific values: a == 2, b == 3 1) 2, 3 : b...
30 Sep 2018 by maysamfth
hi I have 2 table for sale with below fields: saleDetail (id, commodityID, count, price, ...) commodity (id, parentID, name) commodity table is hierarchical or recursive. There are my test data commodity id-- parentID-- name 1-- null-- foods 2-- 1-- ...
30 Sep 2018 by Maciej Los
Check this: DECLARE @commodity TABLE(id INT IDENTITY(1,1), parentID INT, [name] VARCHAR(30)) INSERT INTO @commodity(parentID, [name]) VALUES(null, 'foods'), (1, 'fruits'), (2, 'apple'), (2, 'orange'), (2, 'melon'), (1, 'sea foods'), (6, 'salmon'), (6, 'shrimp') DECLARE @saleDetail...
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...
17 Nov 2018 by OriginalGriff
What's to explain? Either you understand recursion, or you need to learn it. To learn recursion is simple to do: just learn recursion. The winner method is called with a specific value for n. If it isn't one (i.e. the winning position) it calls itself with n minus one, and uses the result from...
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 ...
18 Jun 2019 by CPallini
A give you a sample code which incidentally (?!) could be used as a building block for your program: #include #include using namespace std; void produce(const vector & v, string s, size_t index) { if ( index == v.size() ) { cout
5 Jul 2019 by OriginalGriff
Calling a function within itself is simple. Think of the classic example: factorials. n! is n * (n-1) * (n-2) * (n-3) until the terms reach 1. E.g.: 4! = 4 * 3 * 2 * 1 6! = 6 * 5 * 4 * 3 * 2 * 1 In C# code (I refuse to write Python, it's a toy language)int Factorial(int n) { if (n
6 Jul 2019 by jsc42
Part of your problem may be that the 'concepts' you state have a slight flaw … 4. Each invocation that does correspond to the base case must call itself with parameter(s) that move the execution closer to the base case. The function’s recursive execution must converge to the base case. should...
4 Feb 2020 by CPallini
Hint: at each step, you may use the modulo operator (e.g. n % 10 ) to get the last digit of the number (stop if it is 0) and add it to the sum. Then call the next step passing ( n // 10 ).
19 Jul 2020 by Han Bo Sun
This tutorial will show you how to load and display hierarchical structured comments using RESTFul service and JavaScript.
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...
13 Feb 2021 by Luc Pattyn
How many iterations of this loop foreach (Taxon t in children) { taxnav.Add(rootitem.UrlName.ToString(), t); return GetAllTaxonomyChildren(t.Name, taxnav); ...
13 Jun 2021 by Patrice T
Quote: How to get intuition for a specific DP problem Probably the same way as one guess winning numbers of LOTTO. There is no intuition in finding solution to a problem, there is only experience. If a new problem is equivalent to a previously...
8 Sep 2021 by Patrice T
Quote: I test my code on visual studio, it works when N=0, but if N>0, the result will be greater than the correct answer. I think it might be because placeQ calls placeR too many times or something wrong with vaildQ. Stop guessing, make sure...
23 Feb 2022 by Richard MacCutchan
Try this: for key, value in group.items(): if value in group and group[value] != "None": group[key] = group[value] print(group)
13 Apr 2022 by CPallini
consider the simple case of the print_triangle(1) call print_triangle(1): if 1
25 Jun 2022 by OriginalGriff
Compiling does not mean your code is right! :laugh: Think of the development process as writing an email: compiling successfully means that you wrote the email in the right language - English, rather than German for example - not that the email...
25 Jun 2022 by Patrice T
First of all, your code can't be run as is, part is missing. We have to make guesses to have complete code, and this is not good for debugging. I would change the main to : int main(){ int size=7; // cin >> size; // int* array = new...
31 Aug 2022 by CPallini
Quote: while(s[j+1]!='b' && j
28 Oct 2022 by OriginalGriff
n/2 provides the starting point for the prime check. If you think about it, n cannot be divisible by any number larger than n/2 as 2 is the smallest divisor that allows a zero remainder. If you want to see is 11 is prime, then 11 / 2 is 5...
28 Oct 2022 by merano99
The subroutine should actually have a return value and should not output anything itself, so that the main program makes sense. Currently your code looks like this: int prime(int n, int i) { if(i == 1) printf("Yes"); else { ...
4 Jul 2023 by CIZA_1
I am trying to find intermediary activities between keys. There is different connectors between two keys and I want to find the ones which have minimum value due to a calculation which I will explain below. I have dictionaries such as dict2 =...
4 Jul 2023 by Andre Oosthuizen
I might be a little out of my depth here as Python is still an ongoing learning curve for me. From what I could gather, it looks like the logic to handle a case where there are multiple possible paths between two keys is missing. You need to...
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...
10 Jun 2010 by rpg1503_2010
Hi guys,I have a query called permissions which contains an object list that I extracted from a XML file.Find below an example of the xml structure: ...
11 Jun 2010 by Hristo-Bojilov
There's very similar issue right here.You could follow thread suggestions for your problem too.
13 Sep 2010 by TheRadish
HiI am writing a simple programme to search recursively through a hard drive and return a list of all present files. I am using this in a simple Anti-Virus application. I have written the following function for searching through the files and adding them to a list box:'The following...
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
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
1 Nov 2010 by SuperAdministrator
This builds an array of the form ex: {1,2,2}dictKeys.Length=3dictKeys[] = [100,50,25]The dictKeys represents box capacities the NumberOfSubBoxes array ({1,2,2}) indicates that a 100 box has 2 x 50 boxes and each having 2 x 25 boxes.The question is : I want to build another array of...
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...
11 Feb 2011 by klixxx
After searching google for a different term, I realize it's called OCR.Does anyone have experience in using it?http://en.wikipedia.org/wiki/Optical_character_recognition#OCR_software[^]Edit: Just found it!Creating Optical Character Recognition (OCR) applications using Neural Networks[^]
11 Feb 2011 by Manfred Rudolf Bihy
You may want to checkout this site: Open Source OCR Libraries[^]. They are linking to some open source OCR libraries.Cheers!
20 Feb 2011 by fahad munawar
where did you downloaded the this dll i need it !
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...
19 May 2011 by Tsateran
Hello.Let'...
22 May 2011 by kornakar
You should map a list of children to a menu item class. That way each instance of a menu item also contains its children and you can easily iterate them. All you have to do is to select menu items where ParentId=0.MenuItem-class:[Bag(0, Name = "Children", Inverse = true, Lazy =...
3 Jun 2011 by Cyborgx37
A simple F# application that solves Sudoku puzzles. Links to helpful resources are also provided.
7 Jun 2011 by MJ_
Hey, I built a working recursive function that finds the Longest Common Sequence between two strings. http://en.wikipedia.org/wiki/Longest_common_subsequence_problem[^]It works perfectly fine and it is fast cause I use a memiozation table so that I'm not calling something that I've...
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.
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...