recursion-exercises - 1. Prints array elements in reverse...

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

View Full Document Right Arrow Icon

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

View Full DocumentRight Arrow Icon

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

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 1. Prints array elements in reverse order #include <stdio.h> void PrintRev ( int list [ ] , int first, int last ) // Array to be printed, Index of first, last element . { if ( first <= last ) // Initial condition { printf(" %d ", list [last]); // Prints the last element PrintRev ( list, first, last - 1 ) ; // Then processes the rest of the elements } } int main() { int x; //Declaration int Array[10]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Array declaration/initialization for( x=0; x<10; x++) // Ensures that the index does not cross 9 { printf("%d ", Array[x]); // Prints the contents of the array } printf("\nReverse from 10 to 0: "); PrintRev(Array, 0, 9); // Prints the array in reverse order printf("\nReverse from 3 to 0: "); // Prints the first 4 elements in the arrayin reverse order. PrintRev(Array, 0, 3); printf("\n"); return 0; } 2. Counts the Number of 42’s that appear in the first n elements of the array #include <stdio.h> int count_42s(int array, int n) // Array declaration { if (n == 0) // Initial case return 0; if (array[n-1] != 42) // Searches for 42’s in the first n-1 elements of the list. If the last number is 42, the count increases by 1 than the number found in the sub-array. { return (count_42s(array, n-1) ); // Gives the count of 42’s in the first n-1 elements } return (1 + count_42s(array, n-1) ); //Adds 1 to the count of the sub-array if the last element is also 42 } int main() { int answer; // Declaration int length; // Declaration int numbers[10]={23, 42, 25,16,42, 42, 55, 12, 56, 42}; //Array declaration/Initialization length=10; // Initialize length as 10. answer=count_42s(numbers, length); // Gives the count of 42’s among the numbers whose length is 10 (That is there are 10 numbers to be searched ). printf("the answer is %d \n", answer); // Prints the answer as ‘answer’ } 3. Converts decimal to binary #include <stdio.h> void dec_to_bin(int dec); // Function int main() { int decimal; // Declaration of ‘decimal’ printf("Type a decimal number: " ); // Prints the decimal number scanf("%d", &decimal);...
View Full Document

This document was uploaded on 06/12/2011.

Page1 / 9

recursion-exercises - 1. Prints array elements in reverse...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online