Recursion

# Recursion - Enter a number 10 The value returned when n=10...

This preview shows pages 1–2. Sign up to view the full content.

//Recursion example on final #include <stdio.h> int what(int n) { if(n==0) return 2; if(n==1) return 1; return 3+what(n-2)+what(n-1); } void main() { int n; long t; for(int i=0;i<=10;i++) { printf("Enter a number: "); scanf("%d",&n); t=what(n); printf("The value returned when n=%d is %d\n",n,t); } } /* Enter a number: 0 The value returned when n=0 is 2 Enter a number: 1 The value returned when n=1 is 1 Enter a number: 2 The value returned when n=2 is 6 Enter a number: 3 The value returned when n=3 is 10 Enter a number: 4 The value returned when n=4 is 19 Enter a number: 5 The value returned when n=5 is 32 Enter a number: 6 The value returned when n=6 is 54 Enter a number: 7 The value returned when n=7 is 89 Enter a number: 8 The value returned when n=8 is 146 Enter a number: 9 The value returned when n=9 is 238

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Enter a number: 10 The value returned when n=10 is 387 Press any key to continue . . . */ /* find 2^n #include <stdio.h> long two(int n) { if(n==0) return 1; return 2*two(n-1); } void main() { int n; long t; printf("Enter a number: "); scanf("%d",&n); t=two(n); printf("2 to the power of %d is %d\n",n,t); } */ /* Enter a number: 3 2 to the power of 3 is 8 Press any key to continue . . . */ /* Find factorial of a number (4!=4*3*2*1=24) #include <stdio.h> long fact(int n) { if(n==0) return 1; return n*fact(n-1); } void main() { int n; long f; printf("Enter a number: "); scanf("%d",&n); f=fact(n); printf("%d factorial is %d\n",n,f); } */ /* Enter a number: 4 4 factorial is 24 Press any key to continue . . . */...
View Full Document

{[ snackBarMessage ]}

### Page1 / 2

Recursion - Enter a number 10 The value returned when n=10...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online