Question

There are two ways to write loops: (1) iterative, like the for-loops we're used to using,...

There are two ways to write loops: (1) iterative, like the for-loops we're used to using, and (2) recursive. Your prerequisite preparation for this course should have exposed you to both, although your working knowledge of recursive loops may not be as strong as that of iterative loops.

Consider the following iterative function that prints an array of characters backward:

#include <iostream>
#include <cstring>

// print an array backwards, where 'first' is the first index
// of the array, and 'last' is the last index 
void writeArrayBackward(const char anArray[], int first, int last) {
  int i = 0;

  for (i = last; i >= first; i--) {
    std::cout << anArray[i];
  }
  std::cout << std::endl;
}

// test driver
int main() {
  const char *s = "abc123";
  writeArrayBackward(s, 0, strlen(s) - 1);
}

Iterative loops have one set of local variables that come and go with each cycle -- the previous cycles' values for these variables are completely forgotten and only the present matters (in the above case, this refers to the counter variable i). The cycles are executed in series. But in recursive loops, the cycles all coexist at the same time, each with their own set of local variables. The cycles are executed in parallel.  Parallel in this case means simultaneously, not independently, unless parallelism is explicitly used.

We will be using this property of recursion later in the course on more complex data structures. This exercise serves to reinforce your understanding of the simplest form of recursion -- functions that call themselves.

Assignment

Using the above iterative version of writeArrayBackward as a reference, write a recursive version of this function, but with a couple of twists:

1) Your function will only write the Nth character of the array, supplied as a parameter by the caller. This is an example prototype (although you may want to change the return value type, based on the second twist, below).

void writeArrayNthBackward(const char [], int, int, int);

The first three arguments serve the same purpose as in the iterative example. The fourth argument (an int) supplies the N for the Nth character to print in the array. If n == 1, then the string is printed normally in reverse (no characters are dropped). If n == 2, then every "other" character is printed, and so on.

You can constrain N to be 1 <= N <= 3.

Your code does NOT need to output a newline ('endl') within the recursive function itself (as the above iterative version does), you can output the newline after the return of the function.

2) If any of the removed characters in the string were numbers (not letters), output their sum. For example, if your function removed the numbers 3 and 1 from the string 'abc123', the result would be 3 plus 1, which is 4. See the below table for more examples..

Converting a String Digit to an Integer

If you have a string and want to convert a character in the string to an int, there are a few ways to do it. The easiest is probably this one:

char *a = "123";
int n;
n = (int)a[0] - '0';

Notice we can't simply cast a[0] to an int, because that will give us the ASCII code for the character '1', which is 49. We want the value of 'n' to be 1, so by subtracting the ASCII code for 0 (which is 48), it "translates" the character to an integer value.

Homework Answers

Answer #1

Hello there. Here's the function that answers your question.

int writeArrayNthBackward(const char anArray[], int first, int last, int n)
{
if(last<first) //base case
return 0;
int sum=0;
if((strlen(anArray)-last)%n==0) //checking Nth character
{
cout<<anArray[last];
sum+=writeArrayNthBackward(anArray,first,last-1,n);
}
else
{
if(anArray[last]>='0' && anArray[last]<='9') //checking if its an integer
sum+=(anArray[last]-'0');
sum+=writeArrayNthBackward(anArray,first,last-1,n);
}
return sum; //returning the sum as mentioned in part 2.
}

Hope it serves you well.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Part 1 Write a program that reads a line of input and display the characters between...
Part 1 Write a program that reads a line of input and display the characters between the first two '*' characters. If no two '*' occur, the program should display a message about not finding two * characters. For example, if the user enters: 1abc*D2Efg_#!*345Higkl*mn+op*qr the program should display the following: D2Efg_#! 1) Name your program stars.c. 2) Assume input is no more than 1000 characters. 3) String library functions are NOT allowed in this program. 4) To read a...
C++ Write a recursive function that reverses the given input string. No loops allowed, only use...
C++ Write a recursive function that reverses the given input string. No loops allowed, only use recursive functions. Do not add more or change the parameters to the original function. Do not change the main program. I had asked this before but the solution I was given did not work. #include #include using namespace std; void reverse(string &str) { /*Code needed*/ } int main() {    string name = "sammy";    reverse(name);    cout << name << endl; //should display...
STRICT DOWNVOTE IF NOT DONE FULLY, WILL REPORT ALSO IF COPY PASTED OR MODIFIED ANSWER Develop...
STRICT DOWNVOTE IF NOT DONE FULLY, WILL REPORT ALSO IF COPY PASTED OR MODIFIED ANSWER Develop a class, using templates, to provide functionality for a set of recursive functions. The functions specified as recursive must be written recursively (not iterativly). The UML class specifications are provided below. A main will be provided. Additionally, a make file will need to be developed and submitted. ● Recursion Set Class The recursion set template class will implement the template functions. recursionSet -length: int...
STRICT DOWNVOTE IF NOT DONE FULLY, WILL REPORT ALSO IF COPY PASTED OR MODIFIED ANSWER Develop...
STRICT DOWNVOTE IF NOT DONE FULLY, WILL REPORT ALSO IF COPY PASTED OR MODIFIED ANSWER Develop a class, using templates, to provide functionality for a set of recursive functions. The functions specified as recursive must be written recursively (not iterativly). The UML class specifications are provided below. A main will be provided. Additionally, a make file will need to be developed and submitted. ● Recursion Set Class The recursion set template class will implement the template functions. recursionSet -length: int...
Using the following code perform ALL of the tasks below in C++: ------------------------------------------------------------------------------------------------------------------------------------------- Implementation: Overload input...
Using the following code perform ALL of the tasks below in C++: ------------------------------------------------------------------------------------------------------------------------------------------- Implementation: Overload input operator>> a bigint in the following manner: Read in any number of digits [0-9] until a semi colon ";" is encountered. The number may span over multiple lines. You can assume the input is valid. Overload the operator+ so that it adds two bigint together. Overload the subscript operator[]. It should return the i-th digit, where i is the 10^i position. So the first...
Strings The example program below, with a few notes following, shows how strings work in C++....
Strings The example program below, with a few notes following, shows how strings work in C++. Example 1: #include <iostream> using namespace std; int main() { string s="eggplant"; string t="okra"; cout<<s[2]<<endl; cout<< s.length()<<endl; ​//prints 8 cout<<s.substr(1,4)<<endl; ​//prints ggpl...kind of like a slice, but the second num is the length of the piece cout<<s+t<<endl; //concatenates: prints eggplantokra cout<<s+"a"<<endl; cout<<s.append("a")<<endl; ​//prints eggplanta: see Note 1 below //cout<<s.append(t[1])<<endl; ​//an error; see Note 1 cout<<s.append(t.substr(1,1))<<endl; ​//prints eggplantak; see Note 1 cout<<s.find("gg")<<endl; if (s.find("gg")!=-1) cout<<"found...
C++ visual studios this function has to run twice. and the "count" variable needs to be...
C++ visual studios this function has to run twice. and the "count" variable needs to be "2" on the second run. How can i do that? The parameters can not change as well void printArray(const int *array, int n) {    int count = 1;    char check;    if (check == 'k')    {        count++;    }    cout << "Value " << count << " array contents." << endl;    cout << "------------------------" << endl;   ...
Write a program that reads a string and outputs the number of lowercase vowels in the...
Write a program that reads a string and outputs the number of lowercase vowels in the string. Your program must contain a function with a parameter of a char variable that returns an int. The function will return a 1 if the char being passed in is a lowercase vowel, and a 0 for any other character. The output for your main program should be: There are XXXX lowercase vowels in string yyyyyyyyyyyyyyyyyyyyyy Where XXXX is the count of lowercase...
Write up to three lines to explain the logic used behind those codes.        1) #include <iostream>...
Write up to three lines to explain the logic used behind those codes.        1) #include <iostream> #include <string> #include <fstream> #include <vector> #include <sstream> using namespace std; int main() {         ifstream infile("worldpop.txt");         vector<pair<string, int>> population_directory;         string line;         while(getline(infile, line)){                 if(line.size()>0){                         stringstream ss(line);                         string country;                         int population;                         ss>>country;                         ss>>population;                         population_directory.push_back(make_pair(country, population));                 }         }         cout<<"Task 1"<<endl;         cout<<"Names of countries with population>=1000,000,000"<<endl;         for(int i=0;i<population_directory.size();i++){                 if(population_directory[i].second>=1000000000){                        ...
Write a template-based class that implements a template-based implementation of Homework 3 that allows for any...
Write a template-based class that implements a template-based implementation of Homework 3 that allows for any type dynamic arrays (replace string by the template in all instances below). • The class should have: – A private member variable called dynamicArray that references a dynamic array of type string. – A private member variable called size that holds the number of entries in the array. – A default constructor that sets the dynamic array to NULL and sets size to 0....