SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Recursion
Exercise:
Programming Projects
Question:3 | ISBN:9780132846813 | Edition: 5

Question

Write a recursive function that has an argument that is an array of characters and two arguments that are array indexes. The function should reverse the order of those entries in the array whose indexes are between the two bounds. For example, if the array is

a[1] == 'A' a[2] == 'B' a[3] == 'C' a[4] == 'D' a[5] == 'E'

and the bounds are 2 and 5 , then after the function is run, the array elements should be

a[1] == 'A' a[2] == 'E' a[3] == 'D' a[4] == 'C' a[5] == 'B'

Embed the function in a program and test it. After you have fully debugged this function, define another function that takes a single argument that is an array that contains a string value; the function should reverse the spelling of the string value in the array argument. This function will include a call to the recursive definition you did for the first part of this project. Embed this second function in a program and test it.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

#include<iostream>
#include<cmath>
using namespace std;
void recurseReverse(int a[], int firstIndex, int secondIndex)
{
   int temp;
   if (firstIndex >= secondIndex)
     return;
   temp = a[firstIndex];   
   a[firstIndex] = a[secondIndex];
   a[secondIndex] = temp;
   recurseReverse(a, firstIndex+1, secondIndex-1);   
}     
void display(int arr[], int size)
{
  int i;
  for (i=0; i < size; i++)
    cout<< arr[i]<<endl;
} 
 
int main()
{
	int arr[] = {1, 25, 33, 40, 50};
	  cout<<"Array elements are:\n";
    display(arr, 5);
    recurseReverse(arr, 0, 4);
    cout<<"Reversed array elements is \n";
    display(arr, 5);    
	system("pause");
	return 0;
} 

Output:

Array elements are:
1
25
33
40
50
Reversed array elements is
50
40
33
25
1

 

0 0

Discussions

Post the discussion to improve the above solution.