C Exercise 28
100 Classic C Language Examples
**Problem:** Five people sit together. How old is the fifth person? He says he is 2 years older than the fourth. The fourth says he is 2 years older than the third. The third says he is 2 years older than the second. The second says he is 2 years older than the first. Finally, the first says he is 10 years old. How old is the fifth person?
**Analysis:** Use recursion, which has two phases: pushing back (recursion) and resolving forward. To know the fifth person's age, you need the fourth person's age, and so on, until you reach the first person (10 years old), then work back forward..
Example
// Created by www.runoob.com on 15/11/9.
// Copyright (c) 2015 Runoob Tutorial. All rights reserved.
//
#include
<
stdio.h
int
age
(
n
)
int
n;
{
int
c
;
if
(
n
==
1
)
c
=
10
;
else
c
=
age
(
n
1
)
2
;
return
(
c
)
;
}
int
main
(
)
{
printf
(
"
%d
\
n
"
,
age
(
5
)
)
;
}
The output of the above example is:
18