C & C++ fundamentals / 14
Return statements and recursion
Use a stopping condition and a recursive function call to print a message repeatedly without a loop.
On this page
In this final introductory lesson on functions, we will look at returning under a specific condition. A return leaves a function. For example, return 0; in main returns the value zero and ends the function.
By choosing when to return, we can make a function repeat work without a loop. The following example prints Hello World multiple times by calling the function again from inside itself:
#include <stdio.h>
void test(int num)
{
if(num < 1)
{
return;
}
test(num-1);
printf("Hello World\n");
}
int main()
{
test(10);
return 0;
}
Follow the calls
main calls test(10). Inside test, the program checks whether num is less than one. If not, it calls test(num - 1), reducing the value from ten to nine and continuing in the same way.
When num reaches zero, the condition is true and the function returns. The waiting calls then resume, each printing Hello World. In total, the message is printed ten times.
This pattern is called recursion: a function calls itself. For suitable problems, recursion can express repeated work compactly and make the overall structure easier to follow.
Editorial note: the recursive call appears before
printf, so printing occurs while the calls return, not before descending to zero. Becausetestreturnsvoid, its stopping branch usesreturn;, notreturn 0;. The original code already used the correct statement, but its prose mixed them up.
Moved here from Tistory
I migrated this post from my Korean Tistory blog, I am Jason Lee, to this website and translated it into English. My writing and projects now live together in one place.
The original publication date, code examples, and screenshots are preserved. Editorial notes clarify known issues in the original material.
Original post on Tistory English edition · Aug 30, 2026