這是一個(gè)遞歸函數(shù)調(diào)用的例子。程序中函數(shù)f o r w a r d _ a n d _ b a c k w a r d s ( )的功能是顯示一個(gè)字符串后反向顯示該字符串。
[例4-17] 計(jì)算1~7的平方及平方和。
#include
# include
void header(); / *函數(shù)聲明* /
void square(int number);
void ending();
int sum; /* 全局變量* /
m a i n ( )
{
int index;
h e a d e r ( ) ; / *函數(shù)調(diào)用* /
for (index = 1;index <= 7;i n d e x + + )
s q u a r e ( i n d e x ) ;
e n d i n g ( ) ; / *結(jié)束* /
}
void header()
{
sum = 0; /* 初始化變量"sum" */
printf("This is the header for the square program\n;\n")
}
void square(int number)
{
int numsq;
numsq = number * numbe;r
sum += numsq;
printf("The square of %d is %d\,nn"u m b e r ,nu m s q ) ;
}
void ending()
{
printf("\nThe sum of the squares is %d,\ns"u m ) ;
}
運(yùn)行程序:
R U N ¿
This is the header for the square program
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
The square of 4 is 16
The square of 5 is 25
The square of 6 is 36
The square of 7 is 49
The sum of the squares is 140
這個(gè)程序打印出1到7的平方值,最后打印出1到7的平方值的和,其中全局變量s u m在多個(gè)
函數(shù)中出現(xiàn)過。
全局變量在h e a d e r中被初始化為零;在函數(shù)s q u a r e中,s u m對n u m b e r的平方值進(jìn)行累加,也就是說,每調(diào)用一次函數(shù)s q u a r e和s u m就對n u m b e r的平方值累加一次;全局變量s u m在函數(shù)
e n d i n g中被打印。