Polynomial.h
// Polynomial class definition.
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
class Polynomial
{
public:
Polynomial();
void enterTerms();
void printPolynomial() const;
~Polynomial(); // destructor
private:
int numberOfTerms;
int exponents[ 100 ]; // exponent array
int coefficients[ 100 ]; // coefficients array
}; // end class Polynomial
#endif
Polynomial.cpp
// Polynomial member-function definitions.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <iomanip>
using std::showpos;
using std::noshowpos;
#include "Polynomial.h"
Polynomial::Polynomial()
{
for ( int t = 0; t < 100; t++ )
{
coefficients[ t ] = 0;
exponents[ t ] = 0;
} // end for
numberOfTerms = 0;
} // end Polynomial constructor
void Polynomial::printPolynomial() const
{
int start;
bool zero = false;
if ( coefficients[ 0 ] ) // output constants
{
cout << coefficients[ 0 ];
start = 1;
zero = true; // at least one term exists
}
else
{
if ( coefficients[ 1 ] )
{
cout << coefficients[ 1 ] << 'x'; // constant does not exist
// so output first term
// without a sign
if ( ( exponents[ 1 ] != 0 ) && ( exponents[ 1 ] != 1 ) )
cout << '^' << exponents[ 1 ];
zero = true; // at least one term exists
} // end inner if
start = 2;
} // end else
// output remaining polynomial terms
for ( int x = start; x < 100; x++ )
{
if ( coefficients[ x ] != 0 )
{
cout << showpos << coefficients[ x ] << noshowpos << 'x';
if ( ( exponents[ x ] != 0 ) && ( exponents[ x ] != 1 ) )
cout << '^' << exponents[ x ];
zero = true;
} // end if
} // end for
// at least one term exists
if ( !zero ) // no terms exist in the polynomial
cout << '0';
cout << endl;
} // end function printPolynomial
void Polynomial::enterTerms()
{
bool found = false;
int c, e, term;
cout << "\nEnter number of polynomial terms: ";
cin >> numberOfTerms;
for ( int n = 1; n <= numberOfTerms; n++ )
{
cout << "\nEnter coefficient: ";
cin >> c;
cout << "Enter exponent: ";
cin >> e;
if ( c != 0 )
{
// exponents of zero are forced into first element
if ( e == 0 )
{
coefficients[ 0 ] += c;
continue;
} // end if
for ( term = 1; ( term < 100 ) && ( coefficients[ term ] != 0 ); term++ )
if ( e == exponents[ term ] )
{
coefficients[ term ] += c;
exponents[ term ] = e;
found = true; // existing exponent updated
} // end if
if ( !found ) // add term
{
coefficients[ term ] += c;
exponents[ term ] = e;
} // end if
} // end outer if
} // end outer for
} // end function endTerms
// destructor
Polynomial::~Polynomial()
{
// empty destructor
} // end destructor
Solution.cpp
// Polynomial test program.
#include <iostream>
#include <conio.h>
using namespace std;
#include "Polynomial.h"
int main()
{
Polynomial a, b;
a.enterTerms();
b.enterTerms();
cout << "First polynomial is:\n";
a.printPolynomial();
cout << "Second polynomial is:\n";
b.printPolynomial();
cout << endl;
getch();
return 0;
} // end main
© Copyright 2026 Paperzz