# extra - int x int Array[10]={1 2 3 4 5 6 7 8 9 10 for x=0...

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

Below are three problems that will give you some more practice with recursion and using arrays. Try them before you look at the solutions which begin on the next page. 1) Write a recursive function that prints an array in reverse order. void PrintRev ( int list [ ] , int first, int last ) 2) Write a recursive function that checks an array for the number of occurrences of the number 42 found in that array. int count_42s(int array[], int n) 3) Write a recursive function that takes in an array as input, and also two integers, first and last, and sums the array from the index first to the index last. int sum(int first, int last, int array[]) COP 3502 – Summer 2002 Practice Problems – Recursion and Arrays

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

View Full Document
Solution to Problem #1 #include <stdio.h> void PrintRev ( int list [ ] , int first, int last ) { if ( first <= last ) { printf(" %d ", list [last]); // print last element PrintRev ( list, first, last - 1 ) ; // then process the rest } // Base case is empty else-clause } int main()

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: { int x; int Array[10]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for( x=0; x<10; x++) { printf("%d ", Array[x]); } printf("\nReverse from 0 to 10: "); PrintRev(Array, 0, 9); printf("\nReverse from 0 to 3: "); PrintRev(Array, 0, 3); printf("\n"); return 0; } Solution to Problem #2 #include <stdio.h> int count_42s(int array, int n) { if (n == 0) return 0; if (array[n-1] != 42) { return (count_42s(array, n-1) ); } return (1 + count_42s(array, n-1) ); } int main() { int answer; int length; int numbers[10]={23, 42, 25, 16, 42, 42, 55, 12, 56, 42}; length=10; answer=count_42s(numbers, length); printf("the answer is %d \n", answer); } Solution to Problem #3 #include <stdio.h> int sum(int first, int last, int array) { if(first == last) return array[first]; /* else */ return (array[first] + sum(first+1,last,array)); } int main() { int Answer; int F[10]={10, 12, 11, 1, 15, 10, 2, 3, 4, 9}; Answer=sum(1, 9, F); printf("The answer is : %d\n", Answer); return 0; }...
View Full Document

{[ snackBarMessage ]}

### Page1 / 4

extra - int x int Array[10]={1 2 3 4 5 6 7 8 9 10 for x=0...

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

View Full Document
Ask a homework question - tutors are online