C/Function/Function Recursive
Содержание
A recursive power function
<source lang="cpp">
- include <stdio.h>
double power(double x, int n); int main() {
double x = 0.0; int n = 0; for(x = 2.0 ; x<= 5.0; x += 0.5) for(n = 0 ; n<5 ; n++) printf("%.2lf raised to the power %d = %.2lf\n", x, n, power(x,n));
} /* Function to raise x to the power n.*/ double power(double x, int n) {
if(n == 0) return 1.0; else return x * power( x , n - 1 );
}
</source>
Calculating factorials using recursion
<source lang="cpp">
- include <stdio.h>
long factorial(long); void main() {
long number = 0; printf("\nEnter an integer value: "); scanf(" %ld", &number); printf("\nThe factorial of %ld is %ld\n", number, factorial(number));
} /* recursive factorial function */ long factorial(long N) {
if( N < 2 ) return N; else return N*factorial(N - 1);
}
</source>
Copy string using recursion
<source lang="cpp">
- include <stdio.h>
void strcopy(char *s1, char *s2); int main(void) {
char str[80]; strcopy(str, "this is a test"); printf(str); return 0;
}
void strcopy(char *s1, char *s2) {
if(*s2) { /* if not at end of s2 */ *s1++ = *s2++; strcopy(s1, s2); } else *s1 = "\0"; /* null terminate the string */
}
</source>
Function: Recursive call
<source lang="cpp">
- include <stdio.h>
void f(int i); int main(void) {
f( 0 ); return 0;
} void f(int i) {
if( i < 10) { f( i + 1 ); /* recursive call */ printf("%d ", i); }
}
</source>
Prints out Fibonacci numbers
<source lang="cpp">
- include <stdio.h>
int main() {
int old_number= 1; int current_number = 1; int next_number; while (current_number < 100) { printf("%d\n", current_number); next_number = current_number + old_number; old_number = current_number; current_number = next_number; } return (0);
}
</source>
Recursive function call
<source lang="cpp">
- include <stdio.h>
int add(int pk,int pm); main() {
int k = 2; int i; int m = 3; i = add(k,m); printf("i = %d\n",i);
} int add(int addk,int addm) {
if(addm==0) return(addk); else return(1+add(addk,addm-1));
}
</source>
Recursive function with static variable
<source lang="cpp">
- include <stdio.h>
void f(void); int main(void) {
f(); return 0;
} void f(void) {
static int s = 0; s++; if(s == 10) return; printf("%d ", s); f(); /* recursive call */
}
</source>