What will this Recursive function in C Print and what is the logic behind it?
#include <stdio.h>
int display(int x)
{
if (x < 0)
{
return (0);
}
printf("%d", x + display(x - 1));
x--;
return (x);
}
int main(void)
{
display(4);
return (0);
}
To be able to find what the above program will print, you need to understand recursion and how recursive functions work.
The simplest way will be to run the code in a compiler, but being able to deduce it based on the logic of the program is what the question seeks.
I am going to go on and explain the logic behind the code, presuming that you know about recursion and recursive functions. If you have no idea about them, then try and read on them before.
Since the question is looking for the output, we have to be interested in any line of code that prints out something to the screen.
In the code above, you can see that there is only one line that prints out something to the screen and that line is:
printf("%d", x + display(x - 1));
However, the print line even though within the display()
function also calls another display()
function which makes the function a recursive function.
The presence of the recursion of the function also draws our attention to the return value for the function. This is because, the return value is what will be provided anywhere the function is called.
This means that we need to figure out both what is printed out and what is returned in order to get the right output for the whole code.
Let's therefore take them one by one.
What does this function do and what does it return
int display(int x)
{
if (x < 0)
{
return (0);
}
printf("%d", x + display(x - 1));
x--;
return (x);
}
The first line of the body of the function checks to see if the variable (x
) passed to it is less than zero and returns zero if that is true.
The function then goes on to print the sum of the variable plus the return value of the display()
function when the argument for the function is x-1
.
In the next line, there is a decrement on the variable x
before returning the current value of x
. The decrement on x
means that, we will subtract one from x
and return the resulting value.
This means that every time, the display()
function is called, it returns one less than the number that was passed to it as an argument. An example will be if we call display(2)
, then it is going to return 2-1
which be 1
.
Since the question gave display(4)
, it means we need to have the return values for 4, then the printf
statement in there will also require the return value for 3 which in turn will require return values for 2, etc.
We will have to keep reducing the numbers till we get to zero. So, let's have a table with the numbers and their return values:
Display function argument | Return value |
4 | 3 |
3 | 2 |
2 | 1 |
1 | 0 |
0 | -1 |
-1 | 0 |
Now that we know what the function does and the values it returns at each stage, we can go ahead look at what the function prints at each stage.
What does the function print at each stage?
printf("%d", x + display(x - 1));
At each stage, the function prints the sum of the argument (x)
passed to the function and the return value of the display()
function with argument of one less than the initial argument (x-1)
.
Since we know that, the function in the question above runs multiple times with values starting from 4
down to 0
, we have to find the value that will be printed with each value.
Let's use a table to illustrate that.
Display function argument | What to print value | Argument + Return value | Value printed |
4 | 4 + return value for display(3) | 4 + 2 | 6 |
3 | 3 + return value for display(2) | 3 + 1 | 4 |
2 | 2 + return value for display(1) | 2 + 0 | 2 |
1 | 1 + return value for display(0) | 1 + -1 | 0 |
0 | 0 + return value for (-1) | 0 + 0 | 0 |
Because of the recursion, the code will print that of display(0)
first followed by display(1)
then continuously till the last one (display(4)
in this case) is printed.
As such, you have the final output being:
00246
Conclusion
I hope I was able to simplify this enough but if you have questions on any of the things I explained above or have some suggestions, you can comment it down below or hit me up on Twitter via a DM and let's chat it out.
Thanks for reading.
Subscribe to my newsletter
Read articles from Dr. Ehoneah Obed directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Dr. Ehoneah Obed
Dr. Ehoneah Obed
Heya! One thing I love doing is helping people and I believe one of the key ways I do this is through sharing of my knowledge and personal experiences. I have therefore decided to use this platform to share my knowledge and experience to people who may decide to take the path that I have taken. So, the question is, what is this path? I am professionally trained as a pharmacist but I have been an ardent lover and user of various technologies. During my practice at a tertiary hospital in the Northern Region of Ghana, I discovered a number of pertinent health problems and how technology can be used to solve those problems. In my quest for finding ways to solve some of these health problems with technology, I discovered the field of digital health and how that is transforming the way healthcare is being delivered. I am so much interested in the field and look forward to building a career in digital health and hopefully starting a company (startup) in that field. To make this career transition, I have to pursue further education and I have come across several paths that can lead to that career goal of mine. I have therefore decided to explore almost all the options that I have. For further studies, some of the courses which I came across that can help me achieve that career goal include a masters program or PHD in any of the following: Digital Health, Health technology, Health Informatics, Information Technology, Computer Science and Computational Science. I have therefore started applying to various schools offering any of the programs above. In the time being, I decided to start learning more about emerging technologies and that led me to take a three months course in Amazon Web Services (AWS). I am currently an AWS Certified Cloud Practitioner. During the 3 months training that I undertook at Ghana Tech Lab, Accra, I was introduced to a lot of things which excited me the more. I came to realize the potential of things I could do if I had the right knowledge especially in software development. Prior to this time, I had taught myself a number programming languages, libraries and frameworks for web development. I could consider myself as a fullstack developer with knowledge in HTML, CSS, Javascript, PHP, MySQL, WordPress, React, Laravel, and Codeigniter. However, I practiced less and didn't feel confident enough about my knowledge. I just knew I needed more. More learning, more practice, more projects and more connections with people in the industry. I started taking the Odin project to become a better web developer and a few days into it, I came across the ALX Software Engineering programme for Africans. Once I realized it was free to join, I was going to do everything in my capacity to qualify for it. I discovered the programme about 3 days to the deadline for the May 2022 Cohort. I therefore, sat through that night to finish my application to ALX. Fortunately for me, I got accepted into the program and a new phase of my life has started. I am now a Software Engineering Student looking forward to building a career in digital health. I know that this is just the beginning. As part of this programme, we spend about 70 hours a week learning, practicing, completing projects and building new relationships with our peers. As part of this journey, I am going to use this platform to document what I learn and share my journey to becoming a Software Engineer with you. Therefore, anyone at all looking to transition from their current career to software engineering will find what I post here relevant. Also, if you are a self-taught developer or you are thinking of teaching yourself software development, then you will also enjoy the content I publish here. Throughout my short journey of life, I have realized that we tend to give up on things easily when there is no form of accountability. I am therefore by this platform signing a deal to become accountable to you through sharing with you whatever I learn. Do share your thoughts and comments with me whenever you come across any of my post so I can truly remain accountable to you and never give up on this new found dream of mine.