Question

I tried using the modulo to skip the chars but I doesnt work in some cases....

I tried using the modulo to skip the chars but I doesnt work in some cases.

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 
#include 

// 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.

Input string N Output
abc123 2 2ca (sum of numbers removed: 4)
hello 1 olleh (sum of numbers removed: 0)
hello 3 l (sum of numbers removed: 0)
c1c1c1 2 ccc (sum of numbers removed: 3)

PreviousNext

Homework Answers

Answer #1

/* remove comments in the code to see all the test cases which are given in the question */

/* save code xyz.cpp and compile using g++ xyz.cpp and run ./a.out you will see the output (I also attached screenshot of output) */

#include<iostream>
#include<cstring>

using namespace std;

int writeArrayNthBackward(const char arr[], int start, int len, int skip){
   if(len<=start)
       return 0;
   int n=0;char x;
   for(int i=len-1; i>len-skip; i--){
       x=arr[i];
       if(x>='0' && x <= '9'){
           n += (int)arr[i]-'0';
       }
   }
   cout<<arr[len-skip];
   n += writeArrayNthBackward(arr, start, len-skip, skip);
   return n;
}

int main(){
   const char *s = "abc123";
   const char *d = "hello";
   const char *a = "c1c1c1";
   int v;
   v=writeArrayNthBackward(s, 0, strlen(s), 2);
   cout<<"(sum of numbers removed: "<<v<<")"<<endl; //uncomment below test cases to see output of all the testcases
/*   v=writeArrayNthBackward(d, 0, strlen(d), 1);
   cout<<"(sum of numbers removed: "<<v<<")"<<endl;
   v=writeArrayNthBackward(d, 0, strlen(d), 3);
   cout<<"(sum of numbers removed: "<<v<<")"<<endl;
   v=writeArrayNthBackward(a, 0, strlen(a), 2);
   cout<<"(sum of numbers removed: "<<v<<")"<<endl;
*/
   return 0;
}

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
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...
Please follow ALL the instructions and solve it by C++. Please and thank you! There are...
Please follow ALL the instructions and solve it by C++. Please and thank you! 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...
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...
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...
You may notice that the function strchr in the <cstring> library searches for a character within...
You may notice that the function strchr in the <cstring> library searches for a character within a string, and returns the memory address (pointer) to where that character first occurs. 1.) Write your own version of the strchr function, int findchr( char text[ ], char target) , which returns the index of the first occurrance of the character target if it occurs within the string text. If target does not occur within the string, a -1 is to be returned....
void reverse_in_place(string& s){ int last = s.length() -1; for (int i = 0; i <= last/2;...
void reverse_in_place(string& s){ int last = s.length() -1; for (int i = 0; i <= last/2; i++){ char temp = s[i]; //i is initially 0 s[i] = s[last-1]; //swapping first and last character s[last- i] = temp; } } This is a c++ program. convert the same function for array and vectors.
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...
What is wrong with my recursive Binary Search code? For some reason my 'middle' value is...
What is wrong with my recursive Binary Search code? For some reason my 'middle' value is always zero? Please fix and explain! #include <stdio.h> #include <stdlib.h> #include <stdbool.h> int BinarySearch(const int A[],const int L,const int R,const int key) {              if (R >= 1){           int middle = L + (R-1)/2;                              if (A[middle] == key)        return A[middle];               if (A[middle] > key){...
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...