C Exercise Example 28

100 Classic C Examples

Title:There are five people sitting together. Ask the fifth person how old he is. He says he is 2 years older than the fourth person. Ask the fourth person his age, he says he is 2 years older than the third person. Ask the third person, he again says he is 2 years older than the second person. Ask the second person, he says he is 2 years older than the first person. Finally ask the first person, he says he is 10 years old. So, how old is the fifth person?

Program analysis:Using the recursive method, recursion is divided into two stages: backward reasoning and forward reasoning. To know the fifth person's age, one needs to know the fourth person's age, and so on, reasoning forward to the first person (10 years old), then reasoning backward.

Example

// Created by www.example.com on 15/11/9. // Copyright © 2015 Example. 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

100 Classic C Examples

other extensions