给你几个比较经典的例子
递归调用
#include<stdio.h>
void main()
{
int w = 2;
void fun(int);
fun(w);
printf("\n");
}
void fun(int k)
{
if(k>0)
fun(k-1);
printf("%d\t",k);
}
输出的结果是0
1
2
第n个人说他比第n-1个人大2岁;第n-1个人说他比第n-2个人大2岁;……第2个人说他比第2个人大2岁;第一个说他10岁,问第n个人多大
#include<stdio.h>
void main()
{
int n;
printf("the number of people:");
scanf("%d",&n);
int age(int a);
printf("the age of %dth people is: %d.\n",n,age(n));
}
int age(int a)
{
if (a==1)
return 10;
else
return age(a-1) + 2;
}
求年龄的
求n的阶乘
#include<stdio.h>
int fun(int n);
void main()
{
int n;
printf("the number of n:");
scanf("%d",&n);
printf("the fun(%d) = %d.\n",n,fun(n));
}
int fun(int n)
{
if(n == 1)
return 1;
while(n != 1)
return n*fun(n-1);
}
M到n的和递归
#include<stdio.h>
int sum(int a,int b);
void main()
{
int m,n;
printf("input two numbers m and n:");
scanf("%d%d",&m,&n);
if (m > n)
printf("%d.\n",sum(m,n));
else
printf("input error.\n");
}
int sum(int a,int b)
{
if(a == b)
return a;
else
return b+sum(a,b+1);
}
斐波那契数列
#include<stdio.h>
int fi(int a);
void main()
{
int n;
printf("the number of ouput:");
scanf("%d",&n);
printf("F[%d] = %d.\n",n,fi(n));
}
int fi(int a)
{
if(a == 1||a == 2)
return 1;
else
return fi(a-1)+fi(a-2);
}