A sequence of integers such as 1, 3, 5, 7, ... can be represented by a function
ID: 3847311 • Letter: A
Question
A sequence of integers such as 1, 3, 5, 7, ... can be represented by a function that takes a nonnegative integer as parameter and returns the corresponding term of the sequence. For example, the sequence of odd numbers just cited can be represented by the function
int odd(int k) {return 2 * k + 1;}
Write an abstract class AbstractSeq that has a pure virtual member function
virtual int fun(int k) = 0;
as a stand-in for an actual sequence, and two member functions
void printSeq(int k, int m); int sumSeq(int k, int m)
that are passed two integer parameters k and m, where k < m. The function printSeq will print all the terms fun(k) through fun(m) of the sequence, and likewise, the function sumSeq will return the sum of those terms. Demonstrate your AbstractSeq class by creating subclasses that you use to sum the terms of at least two different sequences. Determine what kind of output best shows off the operation of these classes, and write a program that produces that kind of output.
Explanation / Answer
Here is the answer for your question with output. Please don't forget to rate the answer if it helped. Thank you very much.
#include <iostream>
using namespace std;
class AbstractSeq
{
public:
virtual int fun(int k) = 0;
void printSeq(int k, int m)
{
cout << "sequence terms from " << k << "th term to " << m <<"th term" << endl;
for(int i = k ; i <= m; i++)
cout << fun(i) << ", " ;
cout << endl;
}
int sumSeq(int k, int m)
{
int sum = 0;
for(int i = k ; i <= m; i++)
sum += fun(i) ;
return sum;
}
};
//representing odd numbers 1, 3, 5, 7...
class OddSequence : public AbstractSeq
{
public:
int fun(int k)
{
return 2 * k + 1;
}
};
//represent square numbers 1, 2, 9, 16, 25 , ....
class SquareSequence : public AbstractSeq
{
public:
int fun(int k)
{
return (k+1)*(k+1);
}
};
int main()
{
int k, m;
OddSequence odd;
SquareSequence square;
cout << "Enter starting term number in sequence (starting from 0) k: ";
cin >> k;
cout << "Enter ending term number in sequence (starting from 0) m: ";
cin >> m;
cout<<"Odd sequence: ";
odd.printSeq(k, m);
cout<<"Sum of odd sequence: " << odd.sumSeq(k , m) << endl << endl;
cout<<"Sqare sequence: ";
square.printSeq(k, m);
cout<<"Sum of square sequence: " << square.sumSeq(k , m) << endl << endl;
}
output
Enter starting term number in sequence (starting from 0) k: 0
Enter ending term number in sequence (starting from 0) m: 4
Odd sequence: sequence terms from 0th term to 4th term
1, 3, 5, 7, 9,
Sum of odd sequence: 25
Sqare sequence: sequence terms from 0th term to 4th term
1, 4, 9, 16, 25,
Sum of square sequence: 55
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.