

{"id":123290,"date":"2024-02-12T18:00:51","date_gmt":"2024-02-12T12:30:51","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=123290"},"modified":"2024-03-09T14:10:19","modified_gmt":"2024-03-09T08:40:19","slug":"c-program-to-reverse-a-number-using-recursion","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/c-program-to-reverse-a-number-using-recursion\/","title":{"rendered":"C Program to Reverse a Number using Recursion"},"content":{"rendered":"<p>A function can call itself thanks to the effective programming technique known as recursion. This method can be applied to elegantly resolve issues that can be divided into smaller issues. Reversing a number is one such issue that can be resolved recursively by gradually extracting and adding the digits.<\/p>\n<p>Reversing a number simply means changing the order of its digits. For example, reversing 123 would result in 321. Being able to reverse a number programmatically is a common interview question and a good way to get familiar with recursion.<\/p>\n<p>In C, we can leverage recursion to reverse a number with just a few lines of code. The key is to continuously divide the number by 10, extract the last digit using the modulo operator, and accumulate it into the result. This article will walk through this recursive approach step-by-step.<\/p>\n<h2>Prerequisites<\/h2>\n<p><strong>To follow along with this article, readers should have:<\/strong><\/p>\n<ul>\n<li>Basic understanding of C programming constructs like functions, loops, and operators<\/li>\n<li>Familiarity with the modulo (%) operator and integer division<\/li>\n<li>Understanding of recursion and how recursive functions work<\/li>\n<\/ul>\n<h3>Overview Of Recursion in C<\/h3>\n<p>Recursion is a problem-solving method where a function repeatedly calls itself. <strong>The characteristics of a recursive function are as follows:<\/strong><\/p>\n<ul>\n<li><strong>Base case &#8211;<\/strong> A simple case where the function does not recurse further<\/li>\n<li><strong>Recursive call &#8211;<\/strong> Function calling itself with different inputs<\/li>\n<\/ul>\n<p>Recursion is useful when a problem can be broken down into simpler sub-problems. Each recursive call works on a smaller sub-problem until the base case is reached.<\/p>\n<p><strong>For example, calculating the factorial of a number lends itself well to a recursive solution:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int factorial(int n) {\r\n  if (n == 0) { \/\/ base case\r\n    return 1; \r\n  }\r\n  \r\n  return n * factorial(n-1); \/\/ recursive call\r\n}<\/pre>\n<p>Here, the factorial function calls itself with n-1 until n == 0. Recursion provides an elegant solution in this case.<\/p>\n<h3>Recursive Approach<\/h3>\n<p><strong>The recursive approach is to successively extract the last digit and accumulate it into the result:<\/strong><\/p>\n<ul>\n<li>Extract the last digit using % 10<\/li>\n<li>Append it to the recursive call operating on the remaining number (divided by 10)<\/li>\n<li>The recursion stops when the number becomes 0 (base case)<\/li>\n<\/ul>\n<p><strong>For example, to reverse 123:<\/strong><\/p>\n<ul>\n<li>Extract 3, append it to reverse(12) =&gt; 3 + reverse(12)<\/li>\n<li>Extract 2, append it to reverse(1) =&gt; 3 + 2 + reverse(1)<\/li>\n<li>Extract 1, append it to reverse(0) =&gt; 3 + 2 + 1 + reverse(0)<\/li>\n<li>Base case, return 0<\/li>\n<\/ul>\n<p><strong>Here is a recursive pseudocode implementation:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">reverse(num)\r\n  if num == 0 \r\n    return 0\r\n  digit = num % 10\r\n  return digit + 10 * reverse(num \/ 10)<\/pre>\n<p>&nbsp;<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2024\/02\/recursive-approach.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-134530 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2024\/02\/recursive-approach.webp\" alt=\"recursive approach\" width=\"600\" height=\"315\" \/><\/a><\/p>\n<h3>Implementation in C<\/h3>\n<p><strong>Here is the C implementation of recursively reversing a number:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ Recursive function to reverse a number \r\nint reverse(int num) {\r\n\r\n  \/\/ Base case\r\n  if (num == 0)  \r\n    return 0;\r\n\r\n  \/\/ Extract last digit and append to reversed number \r\n  int digit = num % 10; \r\n  int reversed = digit + 10 * reverse(num \/ 10);\r\n\r\n  return reversed;\r\n}\r\n\r\n\/\/ Driver code\r\nint main() {\r\n  int num = 12345;\r\n  int reversed = reverse(num); \r\n  printf(\"Reversed number is: %d\", reversed);\r\n\r\n  return 0;\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\n<strong>Reversed number is:<\/strong> 54321<\/p>\n<ul>\n<li>The reverse function is defined to reverse an integer num recursively.<\/li>\n<li>In the reverse function, there&#8217;s a base case: if num is equal to 0, it returns 0. This is the termination condition for the recursion.<\/li>\n<li>If num is not 0, it proceeds with the reversal process.<\/li>\n<li>The last digit of num is extracted using the modulo operator % and stored in the variable digit.<\/li>\n<li>The function then calls itself recursively with the remaining part of the number after removing the last digit (num \/ 10).<\/li>\n<li>The result of the recursive call is multiplied by 10 and added to the digit. This effectively appends the last digit to the reversed number.<\/li>\n<li>This process continues until the base case is reached, and the recursion starts to unwind.<\/li>\n<li>The reversed number is built up as the recursion unwinds, and eventually, the fully reversed number is returned.<\/li>\n<li>In the main function, an integer num is initialized with the value 12345.<\/li>\n<li>The reverse function is called with num, and the result is stored in the reversed variable.<\/li>\n<li>Finally, the reversed number is printed using printf.<\/li>\n<\/ul>\n<p>This recursively extracts and accumulates each digit to build the final reversed number.<\/p>\n<h3>Time and Space Complexity<\/h3>\n<p>The time complexity of the algorithm is denoted as O(n), where &#8216;n&#8217; signifies the count of digits in the input. This complexity arises from the fact that the algorithm involves extracting a digit and making a recursive call for each digit in the input, leading to a linear relationship between the execution time and the size of the input.<\/p>\n<p>On the other hand, the space complexity is also O(n). This is primarily due to the space required for the recursion stack, which grows in proportion to the number of recursive calls made by the algorithm. Since the number of recursive calls is directly tied to the size of the input (number of digits), the space complexity is linear relative to the input size.<\/p>\n<h3>Conclusion<\/h3>\n<p>This article demonstrated how to recursively reverse a number in C &#8211; from the concept and algorithm to implementation and testing. The elegance of recursion lies in breaking a problem down into simpler sub-problems.<\/p>\n<p>Mastering recursion in C will equip you with a powerful technique to solve a variety of algorithmic problems. Starting with reversing a number serves as an excellent first step. Readers are encouraged to apply recursion to other problems like computing Fibonacci numbers.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>A function can call itself thanks to the effective programming technique known as recursion. This method can be applied to elegantly resolve issues that can be divided into smaller issues. Reversing a number is&#46;&#46;&#46;<\/p>\n","protected":false},"author":86671,"featured_media":123818,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[19488],"tags":[29957,23914,2263,29219,29252,29958],"class_list":["post-123290","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c-programming","tag-c-program-to-reverse-a-number-using-recursion","tag-c-programming","tag-c","tag-c-practical","tag-c-reverse-a-number","tag-reversing-a-number-using-recursion"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>C Program to Reverse a Number using Recursion - DataFlair<\/title>\n<meta name=\"description\" content=\"Reversing a number simply means changing the order of its digits. The elegance of recursion lies in breaking a problem down into simpler sub-problems.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/c-program-to-reverse-a-number-using-recursion\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"C Program to Reverse a Number using Recursion - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Reversing a number simply means changing the order of its digits. The elegance of recursion lies in breaking a problem down into simpler sub-problems.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/c-program-to-reverse-a-number-using-recursion\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2024-02-12T12:30:51+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-03-09T08:40:19+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/c-program-to-reverse-a-number.webp\" \/>\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\/webp\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\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=\"4 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"C Program to Reverse a Number using Recursion - DataFlair","description":"Reversing a number simply means changing the order of its digits. The elegance of recursion lies in breaking a problem down into simpler sub-problems.","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:\/\/data-flair.training\/blogs\/c-program-to-reverse-a-number-using-recursion\/","og_locale":"en_US","og_type":"article","og_title":"C Program to Reverse a Number using Recursion - DataFlair","og_description":"Reversing a number simply means changing the order of its digits. The elegance of recursion lies in breaking a problem down into simpler sub-problems.","og_url":"https:\/\/data-flair.training\/blogs\/c-program-to-reverse-a-number-using-recursion\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2024-02-12T12:30:51+00:00","article_modified_time":"2024-03-09T08:40:19+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/c-program-to-reverse-a-number.webp","type":"image\/webp"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/c-program-to-reverse-a-number-using-recursion\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/c-program-to-reverse-a-number-using-recursion\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/0e594f928e31fc96628ac40f6ae74f49"},"headline":"C Program to Reverse a Number using Recursion","datePublished":"2024-02-12T12:30:51+00:00","dateModified":"2024-03-09T08:40:19+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/c-program-to-reverse-a-number-using-recursion\/"},"wordCount":778,"commentCount":1,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/c-program-to-reverse-a-number-using-recursion\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/c-program-to-reverse-a-number.webp","keywords":["c program to reverse a number using recursion","c programming","C++","c++ practical","c++ reverse a number","reversing a number using recursion"],"articleSection":["C Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/c-program-to-reverse-a-number-using-recursion\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/c-program-to-reverse-a-number-using-recursion\/","url":"https:\/\/data-flair.training\/blogs\/c-program-to-reverse-a-number-using-recursion\/","name":"C Program to Reverse a Number using Recursion - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/c-program-to-reverse-a-number-using-recursion\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/c-program-to-reverse-a-number-using-recursion\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/c-program-to-reverse-a-number.webp","datePublished":"2024-02-12T12:30:51+00:00","dateModified":"2024-03-09T08:40:19+00:00","description":"Reversing a number simply means changing the order of its digits. The elegance of recursion lies in breaking a problem down into simpler sub-problems.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/c-program-to-reverse-a-number-using-recursion\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/c-program-to-reverse-a-number-using-recursion\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/c-program-to-reverse-a-number-using-recursion\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/c-program-to-reverse-a-number.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/c-program-to-reverse-a-number.webp","width":1200,"height":628,"caption":"c program to reverse a number"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/c-program-to-reverse-a-number-using-recursion\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"C Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/c-programming\/"},{"@type":"ListItem","position":3,"name":"C Program to Reverse a Number using Recursion"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/0e594f928e31fc96628ac40f6ae74f49","name":"TechVidvan Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/c89190da3d4010c71ba476b618ab10fdc2335c82cdfa0ad5002d98d0f2473444?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/c89190da3d4010c71ba476b618ab10fdc2335c82cdfa0ad5002d98d0f2473444?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/c89190da3d4010c71ba476b618ab10fdc2335c82cdfa0ad5002d98d0f2473444?s=96&d=mm&r=g","caption":"TechVidvan Team"},"description":"TechVidvan Team provides high-quality content &amp; courses on AI, ML, Data Science, Data Engineering, Data Analytics, programming, Python, DSA, Android, Flutter, full stack web dev, MERN, and many latest technology.","url":"https:\/\/data-flair.training\/blogs\/author\/test001\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/123290","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/86671"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=123290"}],"version-history":[{"count":7,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/123290\/revisions"}],"predecessor-version":[{"id":134531,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/123290\/revisions\/134531"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/123818"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=123290"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=123290"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=123290"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}