Professional Documents
Culture Documents
Linguagem C
Funo Recursiva
Fatorial
1 - //Recursividade na Linguagem C
2 - //PRC - Prof. Joo
3 - //FATORIAL
4 - #include stdio.h
5 - int fatorial(int x){
6 - if(( x == 0 ) || ( x ==1))
7return 1;
8 - else
9return(x * fatorial(x-1));
10 - }
11 - main(){
12 - int num;
13 - printf("Entre com um nmero: ");
14 - scanf("%d", &num);
15 - printf("O fatorial de %d %d.", num, fatorial(num));
16 - }
Chins Fatorial
5!
120
5*4!
5*(24)
4*3!
4*(6)
3*2!
3*(2)
2*1!
2*(1)
1*0!
1*(1)
1
Fibonacci
1 - //Recursividade na Linguagem C
2 - //PRC - Prof. Joo
3 - //FIBONACCI
4 - #include stdio.h
5 - int fibonacci(int N) {
6 - if( N == 1 )
7return 1;
8 - else
9if( N == 2)
10 return 1;
11 else
12 return(fibonacci(N-1) + fibonacci(N-2));
13 - }
14 - main() {
15 - int num, F;
16 - printf("Entre com um nmero: ");
17 - scanf("%d", &num);
18 - printf("A srie de Fibonacci para %d elementos :\n", num);
19 - for(F=1;F <= num;F++) {
20 printf("%d, ", fibonacci(F));}
21 printf("\nOk");
22 - }
Chins Fibonacci
5
5-1
4
4-1
4-2
5-2
3-1
3-2
3-1
3-2
Somatrio
1 - //Recursividade na Linguagem C
2 - //PRC - Prof. Joo
3 - //SOMATORIO
4 - #include stdio.h
5 - int somatorio(int x) {
6 - if( x == 1 )
7return 1;
8 - else
9return(x + somatorio(x -1));
10 - }
11 - main() {
12 - int num;
13 - printf("Entre com um nmero: ");
14 - scanf("%d", &num);
15 - printf("O somatrio de 0 at %d %d.", num, somatorio(num));
16 - }
Chins Somatrio
5
15
5+Somatorio(4-1)
5+10
5+4+Somatorio(3-1)
5+4+6
5+4+3+Somatorio(2-1)
5+4+3+3
5+4+3+2+Somatorio(1-1)
5+4+3+2+1
5+4+3+2+1+Somatorio(0)
Conta Dgitos
1 - //Recursividade na Linguagem C
2 - //PRC - Prof. Joo
3 - //CONTA DIGITOS
4 - #include stdio.h
5 - int digitos(int x) {
6 - if( abs(x) < 10 )
7return 1;
8 - else
9return(1 + digitos(x/10));
10 - }
11 - main() {
12 - int num;
13 - printf("Entre com um nmero: ");
14 - scanf("%d", &num);
15 - printf("O nmero de dgitos de %d %d.", num, digitos(num));
16 - }
1+digito(12345/10)
1+5
1+1+digito(1234/10)
1+1+4
1+1+1+digito(123/10)
1+1+1+3
1+1+1+1+digito(12/10)
1+1+1+1+2
1+1+1+1+1+digito(1,2/10)
1+1+1+1+1+1
1+1+1+1+1+1+digito(0,12/10)