Easy Tutorial
❮ C Exercise Example63 C Standard Library Signal H ❯

C Exercise Example 28

C Language Classic 100 Examples

Question: There are five people sitting together, and we ask the fifth person how old they are. They say they are 2 years older than the fourth person. When asked about the fourth person's age, they say they are 2 years older than the third person. The third person, in turn, says they are 2 years older than the second person. The second person says they are 2 years older than the first person. Finally, the first person says they are 10 years old. How old is the fifth person?

Program Analysis: Use the method of recursion, which consists of backtracking and forward tracking phases. To know the age of the fifth person, you need to know the age of the fourth person, and so on, until you reach the first person (10 years old), and then backtrack.

Example

//  Created by www.tutorialpro.org on 15/11/9.
//  Copyright © 2015年 tutorialpro.org. 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 above example outputs:

18

C Language Classic 100 Examples

❮ C Exercise Example63 C Standard Library Signal H ❯