Question

Rewrite the C++ code below so the the following conditions are met: You may create any...

Rewrite the C++ code below so the the following conditions are met:

  • You may create any number of classes.
  • You may edit the main() function.
  • Remove the variable string type completely from the entire program. -- Note: Entire program includes all classes, all functions, and main().
  • Get rid of every if and if else statement completely from the entire program. -- Note: Entire program includes all classes, all functions, and main().

Hint: Use polymorphism.

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;

class ArrayFunction {
public:
    ArrayFunction(const string& type) {
        this->type = type; 
    }

    float calculate(float array[], int size) {
        if (type == "mean") {
            float sum = accumulate(array, array + size, 0.0); 
            return sum / size;
        }
        else if (type == "min") {
            return *min_element(array, array+size);
        }
        else if (type == "max") {
            return *max_element(array, array+size);
        }
        else if (type == "first") {
            return array[0];
        }
        return 0;
    }

private:
    string type;
};

int main() {
    float array[] {1,2,3,7};
    vector<ArrayFunction*> functions;
    functions.push_back(new ArrayFunction("mean"));
    functions.push_back(new ArrayFunction("min"));
    functions.push_back(new ArrayFunction("max"));
    functions.push_back(new ArrayFunction("first"));

    for (int i = 0; i < functions.size(); i++) {
        cout << functions[i]->calculate(array, 4) << endl;
        delete functions[i];
    }

    return 0;
}

Example output:

3.25
1
7
1
0 0
Add a comment Improve this question Transcribed image text
Answer #1

program logic:

  • We are going to define to define four different classes:
    • 1.) arrayMean: This will be a parent class. In this calculate() function will be virtual and will return the mean of elemets in array
    • 2.) arrayMax: this will inherit arrayMean. calculate() function wil be overriden to calcualte maximum value in array
    • 3.) arrayMin: this will inherit arrayMean. calcualte() function will be overrriden to calcullate mimimum value in array
    • 4.) arrarFirst: this will inherit from arrayMean. calculate() funciton will be overriden to find first value in array
  • In main(), functions vector will be of type arrayMean*. We will be able to store all its subclass types in the vector.

program:

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;

class ArrayMean {
public:
   
virtual float calculate(float array[], int size) {
float sum = accumulate(array, array + size, 0.0);
return sum / size;
}
};
class ArrayMin: public ArrayMean {
public:
   
float calculate(float array[], int size) override {

return *min_element(array, array+size);
  
}
};

class ArrayMax: public ArrayMean {
public:
   
float calculate(float array[], int size) override {
return *max_element(array, array+size);

}
};


class ArrayFirst: public ArrayMean {
public:
float calculate(float array[], int size) override {
return array[0];
}
};
int main() {
float array[] {1,2,3,7};
vector<ArrayMean*> functions;
functions.push_back(new ArrayMean());
functions.push_back(new ArrayMin());
functions.push_back(new ArrayMax());
functions.push_back(new ArrayFirst());

for (int i = 0; i < functions.size(); i++) {
cout << functions[i]->calculate(array, 4) << endl;
delete functions[i];
}

return 0;
}

output:

3.25 1 7 1

Add a comment
Know the answer?
Add Answer to:
Rewrite the C++ code below so the the following conditions are met: You may create any...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Fix this C++ code so that the function prototypes come before main. Main needs to be...

    Fix this C++ code so that the function prototypes come before main. Main needs to be declared first. Then call to the functions from inside of main. #include<cstdlib> using namespace std; //prompt user for input void getGrades(int gradeArray[],int size) { for(int i=0; i<size; i++) { cout<<"Enter the grade "<<i+1<<": "; cin>>gradeArray[i]; } } // finding average of all numbers in array float computeAverage(int numbers[],int size) { float sum=0; for(int i=0; i<size; i++) { sum = sum + numbers[i]; //compute sum...

  • Rewrite the following C++ code fragments. Your modified code should obey the following rules: • No...

    Rewrite the following C++ code fragments. Your modified code should obey the following rules: • No global variables • No pass-by-reference and pass-by-pointer parameters (except arrays) • No iteration 1 Fibonacci int fib (int n) { if (n <= 1) return 1; int x = 1; int y = 1; int t; for (int i = 2; i <n; i++) { t = x; x = x + y; y = t; return x; 2 Min and max in an...

  • I need to change the following code so that it results in the sample output below...

    I need to change the following code so that it results in the sample output below but also imports and utilizes the code from the GradeCalculator, MaxMin, and Student classes in the com.csc123 package. If you need to change anything in the any of the classes that's fine but there needs to be all 4 classes. I've included the sample input and what I've done so far: package lab03; import java.util.ArrayList; import java.util.Scanner; import com.csc241.*; public class Lab03 { public...

  • Please program in C++ and document the code as you go so I can understand what...

    Please program in C++ and document the code as you go so I can understand what you did for example ///This code does~ Your help is super appreciated. Ill make sure to like and review to however the best answer needs. Overview You will revisit the program that you wrote for Assignment 2 and add functionality that you developed in Assignment 3. Some additional functionality will be added to better the reporting of the students’ scores. There will be 11...

  • Please I need help in C language, I am trying to modify the code per the...

    Please I need help in C language, I am trying to modify the code per the below instructions, but I am getting errors. Can't fgure it out. The attempted code modification and data file is privided below, after the instructions. Thank you. Instructions:                  1.      First, add a function named printMsg that displays a message, a greeting, or an introduction to the program for the user. Add a statement that calls that function from the main function when your program starts....

  • C Programming write two functions, similar to what you see in the sample program. The first will ask the user to enter some information (I have included the type in parentheses) First Name (char[]) L...

    C Programming write two functions, similar to what you see in the sample program. The first will ask the user to enter some information (I have included the type in parentheses) First Name (char[]) Last Name (char[]) Age (int) Height in Inches (double) Weight in Pounds (double) You will use pass-by-reference to modify the values of the arguments passed in from the main(). Remember that arrays require no special notation, as they are passed by reference automatically, but the other...

  • need help editing or rewriting java code, I have this program running that creates random numbers...

    need help editing or rewriting java code, I have this program running that creates random numbers and finds min, max, median ect. from a group of numbers,array. I need to use a data class and a constructor to run the code instead of how I have it written right now. this is an example of what i'm being asked for. This is my code: import java.util.Random; import java.util.Scanner; public class RandomArray { // method to find the minimum number in...

  • May i ask for help with this c++ problem? this is the code i have for assignment 4 question 2: #...

    may i ask for help with this c++ problem? this is the code i have for assignment 4 question 2: #include<iostream> #include<string> #include<sstream> #include<stack> using namespace std; int main() { string inputStr; stack <int> numberStack; cout<<"Enter your expression::"; getline(cin,inputStr); int len=inputStr.length(); stringstream inputStream(inputStr); string word; int val,num1,num2; while (inputStream >> word) { //cout << word << endl; if(word[0] != '+'&& word[0] != '-' && word[0] != '*') { val=stoi(word); numberStack.push(val); // cout<<"Val:"<<val<<endl; } else if(word[0]=='+') { num1=numberStack.top(); numberStack.pop(); num2=numberStack.top(); numberStack.pop();...

  • Write a MIPS assembly code that corresponds to the following C code. Note: use the stack...

    Write a MIPS assembly code that corresponds to the following C code. Note: use the stack to store all register values that you use in the procedures. int aver(int * array, int N){ int i, sum = 0; for ( i=0;i i<N; i++) sum += array[i]; return sum/N;} int Max( int * array, int N){ int i, Maximum = array[i]; for ( i = 1; i< N; i++) if ( array[i] > Maximum) Maximum = array[i]; return Maximum; } int...

  • Remove srand(time(NULL)); from this C++ code so that it still finds random numbers correctly. Then, Write...

    Remove srand(time(NULL)); from this C++ code so that it still finds random numbers correctly. Then, Write a program that adds the following to the fixed code. • Add a function that will use the BubbleSort method to put the numbers in ascending order. – Send the function the array. – Send the function the size of the array. – The sorted array will be sent back through the parameter list, so the data type of the function will be void....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT