{"id":82609,"date":"2021-07-27T09:00:34","date_gmt":"2021-07-27T03:30:34","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=82609"},"modified":"2021-07-27T09:00:34","modified_gmt":"2021-07-27T03:30:34","slug":"recursion-in-c","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/recursion-in-c\/","title":{"rendered":"Recursion in C"},"content":{"rendered":"<p>The C programming language offers various features which help the programmers in making their code efficient and simple. In C, Recursion is one of the most complex and useful concepts.<\/p>\n<p>With the help of recursion, you can solve complex mathematical problems such as factorial of a number and generating fibonacci series etc.<\/p>\n<p>Let us see what is Recursion in C?<\/p>\n<h3>Recursion in C<\/h3>\n<p>In C, When a function calls a copy of itself then the process is known as Recursion. To put it short, when a function calls itself then this technique is known as Recursion. And the function is known as a recursive function.<\/p>\n<p>You have to be more careful when you are using recursion in your program. You just cannot use recursion in all your problems because it will make your program more complex and difficult.<\/p>\n<p>Recursion can be used in case of similar subtasks like sorting, searching, and traversal problems. While using recursion, you will have to define an exit condition on that function, if not then it will go into an infinite loop.<\/p>\n<p><strong>NOTE:-<\/strong> Problems that can be solved recursively, can also be solved iteratively.<\/p>\n<p><strong>Syntax of recursive function in C:-<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">void do_recursion()\n{\n    ... .. ...\n    do_recursion();\n    ... .. ...\n}\nint main()\n{\n    ... .. ...\n   do_recursion();\n    ... .. ...\n}<\/pre>\n<h3>Working of recursion in C:-<\/h3>\n<p>Below is a flowchart of how recursion works:-<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/flow-chart-showing-recursion.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-82918\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/flow-chart-showing-recursion.jpg\" alt=\"flow chart showing recursion in C\" width=\"529\" height=\"747\" \/><\/a><\/p>\n<p>The recursion will go in an infinite loop until some condition is met. So, to prevent it from going into an infinite loop, you can make use of the <strong>if&#8230;else<\/strong> statement or define an exit condition in the recursive function.<\/p>\n<p><strong>Example:- Infinite loop through recursive function<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include&lt;stdio.h&gt;\n\nint main()\n{\n  printf(\"TechVidvan Tutorial: Infinite loop through Recursive Function!\\n\");\n  main();\n  return 0;\n}<\/pre>\n<p>The above example will result in an infinite loop. In the above program, we are doing recursion by calling main() from main(). And also we have not provided any condition for the program to exit. That\u2019s why it will print the output infinitely.<\/p>\n<h3>Types of recursion in C<\/h3>\n<p>There are two types of recursion present in the C programming language.<\/p>\n<ul>\n<li>Direct Recursion<\/li>\n<li>Indirect Recursion<\/li>\n<\/ul>\n<h4>1. Direct Recursion in C<\/h4>\n<p>If a function calls itself directly then the function is known as direct recursive function.<\/p>\n<p><strong>Example:- Direct Recursive function in C<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int fib(int num)\n{\n    if (num==1 || num==2)\n        return 1;\n    else\n        return (fib(num-1)+fib(num-2));\n}<\/pre>\n<p>In the above example, fib() function is direct recursive. Because the statements inside the fib() function calls the fib() function directly.<\/p>\n<h4>2. Indirect Recursion in C<\/h4>\n<p>A function that does not call itself directly then function is known as an indirect recursive function.<\/p>\n<p><strong>Example:- Indirect Recursive function in C<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int first_function(int num)\n{\n    if (num&lt;=2)\n        return 2;\n    else\n        return new_function(num);\n}\nint new_function(int num)\n{\n    return first_function(num);\n}<\/pre>\n<p>In the above example, first_function() calls the new_function(), which is indeed a new function. Then this new_function() calls the first_function(). So, it is an <strong>indirect recursive function.<\/strong><\/p>\n<p><strong>Example:- Finding factorial of a given number<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;stdio.h&gt;  \nint factorial(int);  \nint main()  \n{  \n  int num=5,fact;  \n  printf(\"TechVidvan Tutorial: Factorial of a number using recursion!\\n\\n\");  \n  fact = factorial(num);  \n  printf(\"Factorial of %d is: %d\\n\",num,fact);  \n}  \nint factorial(int num)  \n{  \nif (num==0)  \n{  \nreturn 0;  \n}  \nelse if (num==1)  \n{  \nreturn 1;  \n}  \nelse   \n{  \nreturn num*factorial(num-1);  \n}  \n}<\/pre>\n<p><strong>Output:-<\/strong><\/p>\n<div class=\"code-output\">\n<p>TechVidvan Tutorial: Factorial of a number using recursion!<\/p>\n<p>Factorial of 5 is: 120<\/p>\n<\/div>\n<h3>Recursive Function in C<\/h3>\n<p>A recursive function always performs tasks by dividing it into subtasks. In a recursive function, there has to be an exit() condition and when it is satisfied then the recursion stops and the final result is returned from the function.<\/p>\n<p><strong>For Example:-<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">if (condition1)  \n{  \n  return value1;  \n}  \nelse if (condition2)  \n{  \n  return value2;  \n}  \nelse  \n{  \n  \/\/ Statements;  \n  recursive call;  \n}<\/pre>\n<p><strong>Example:- Recursive Function<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include&lt;stdio.h&gt;  \nint fib(int);  \nvoid main ()  \n{  \n  int num=15,fibo;  \n  printf(\"TechVidvan Tutorial: Fibonacci series using recursive function!\\n\\n\");\n  fibo = fib(num);  \n  printf(\"Result is: %d\",fibo);  \n}  \nint fib(int num)  \n{  \n  if (num==0)  \n  {  \n  return 0;  \n  }  \n  else if (num == 1)  \n  {  \n    \treturn 1;   \n  }  \n  else  \n  {  \n    \treturn fib(num-1)+fib(num-2);  \n  }  \n}<\/pre>\n<p><strong>Output:-<\/strong><\/p>\n<div class=\"code-output\">\n<p>TechVidvan Tutorial: Fibonacci series using recursive function!<\/p>\n<p>Result is: 610<\/p>\n<\/div>\n<h4>Memory allocation of recursive method:-<\/h4>\n<p>In C, each recursive function call creates a copy of it in memory. When some data is returned from the recursive call then the memory releases the copy.<\/p>\n<p>As we all know that all variables, arguments and other things of function get stored in the stack. And for each recursive call, a separate stack is maintained.<\/p>\n<p>Let\u2019s take an example to understand the memory allocation of recursive method.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int print(int num)  \n{  \n  if(num == 0)  \n    \treturn 0;  \n  else   \n  {  \n    \tprintf(\"Value is: %d\",num);  \n    \treturn print(num-1); \/\/ recursive call  \n  }  \n}<\/pre>\n<p>Let\u2019s analyze the above example for num=4. At first, all stacks are maintained. We have used the if condition in the above example. If the value of num reaches 0 then the stacks will be deleted one by one by returning 0 to its calling stack.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/stack-tracing-for-recursive-function-calling.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-82919\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/stack-tracing-for-recursive-function-calling.jpg\" alt=\"stack tracing for recursive function calling\" width=\"1366\" height=\"768\" \/><\/a><\/p>\n<h3>Advantages of Recursion in C<\/h3>\n<ul>\n<li>Makes the program elegant.<\/li>\n<li>It adds clarity to the program code and also reduces the time to write the code.<\/li>\n<li>Reduces time complexity.<\/li>\n<li>It is best for solving problems based on tree structures.<\/li>\n<\/ul>\n<h3>Disadvantages of Recursion in C<\/h3>\n<ul>\n<li>It is slower than non recursive programs due to the overhead of maintaining the stack.<\/li>\n<li>It requires more memory for the stack.<\/li>\n<li>For better performance, use loops instead of recursion. Because recursion is slower.<\/li>\n<\/ul>\n<h3>Significance of Recursion in C<\/h3>\n<p>In C, programmers use recursion many times on their programs due to its ability to keep the code short and simple. It also enhances the code readability.<\/p>\n<p>Recursion also helps in reducing the run-time of the program code. But you can also use iteration, it provides much faster functionality than recursion.<\/p>\n<p>You can solve several problems using the recursion in C. Problems like factorial of a number, fibonacci series in a given range, tree algorithm problems etc. can be solved easily with recursion.<\/p>\n<h3>Why stack overflow occurs in recursion:-<\/h3>\n<p>In recursion, if you don\u2019t specify or define the base case then you can face stack overflow problems.<\/p>\n<p><strong>Example:-<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int factorial(int num)\n{\n    \/\/ wrong base case\nif (num == 10) \n        return 1;\n    else\n        return num*factorial(num-1);\n}<\/pre>\n<p>In the above example, if you provide factorial(5) then first it will call factorial(4), factorial(3) and so on but the number will never reach 10. So, here the base case is not reached then the memory will get exhausted by the factorial() functions on the stack and it will cause a stack overflow error.<\/p>\n<h3>Difference between tailed and non-tailed recursion in C<\/h3>\n<p>In a recursive function, if the recursive call is the last thing executed by the recursive function then the recursive function is known as tail-recursive. And if it is not then it is called a non-tailed recursive.<\/p>\n<h3>Summary<\/h3>\n<p>In this tutorial, we learnt about recursion and recursive functions. We also discussed advantages and disadvantages of using recursion. We also discussed the types of recursion in C.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The C programming language offers various features which help the programmers in making their code efficient and simple. In C, Recursion is one of the most complex and useful concepts. With the help of&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":82914,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3510],"tags":[3848,3849,3850,3851,3852],"class_list":["post-82609","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c-programming","tag-c-recursive-function","tag-direct-recursion","tag-indirect-recursion","tag-recursion-in-c","tag-types-of-recursion-in-c"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Recursion in C - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn about recursion, its types and recursive functions in C. See the advantages and disadvantages of using recursion.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/recursion-in-c\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Recursion in C - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn about recursion, its types and recursive functions in C. See the advantages and disadvantages of using recursion.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/recursion-in-c\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-07-27T03:30:34+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Recursion-in-C.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Recursion in C - TechVidvan","description":"Learn about recursion, its types and recursive functions in C. See the advantages and disadvantages of using recursion.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/recursion-in-c\/","og_locale":"en_US","og_type":"article","og_title":"Recursion in C - TechVidvan","og_description":"Learn about recursion, its types and recursive functions in C. See the advantages and disadvantages of using recursion.","og_url":"https:\/\/techvidvan.com\/tutorials\/recursion-in-c\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-07-27T03:30:34+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Recursion-in-C.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-c\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-c\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Recursion in C","datePublished":"2021-07-27T03:30:34+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-c\/"},"wordCount":957,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-c\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Recursion-in-C.jpg","keywords":["C Recursive function","Direct Recursion","Indirect Recursion","Recursion in C","Types of Recursion in C"],"articleSection":["C Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/recursion-in-c\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-c\/","url":"https:\/\/techvidvan.com\/tutorials\/recursion-in-c\/","name":"Recursion in C - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-c\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-c\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Recursion-in-C.jpg","datePublished":"2021-07-27T03:30:34+00:00","description":"Learn about recursion, its types and recursive functions in C. See the advantages and disadvantages of using recursion.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-c\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/recursion-in-c\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-c\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Recursion-in-C.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Recursion-in-C.jpg","width":1200,"height":628,"caption":"Recursion in C"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-c\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Recursion in C"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/82609","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=82609"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/82609\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/82914"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=82609"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=82609"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=82609"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}