fork download
  1. #include<iostream>
  2. using namespace std;
  3. class polynomial;
  4. class term
  5. {
  6. private:
  7. friend class polynomial;
  8. float coef;
  9. int exp;
  10. };
  11. class polynomial
  12. {
  13. term *termarry;
  14. int capacity,terms;
  15. public:
  16. polynomial();
  17. void display(int);
  18. void add(polynomial);
  19. void newterm(float,int);
  20. };
  21. polynomial::polynomial()
  22. {
  23. capacity=1;
  24. terms=0;
  25. termarry=new term[capacity];
  26. }
  27. void polynomial::newterm(float coef,int ex)
  28. {
  29. if(terms==capacity)
  30. {
  31. capacity*=2;
  32. term *temp=new term[capacity];
  33. copy(termarry,termarry+terms,temp);
  34. termarry=temp;
  35. delete temp;
  36. }
  37. termarry[terms].coef=coef;
  38. termarry[terms++].exp=ex;
  39. }
  40. void polynomial:: add(polynomial b)
  41. {
  42. polynomial c;
  43. int apos=0,bpos=0,cpos=0;
  44. if(termarry[apos].exp==termarry[bpos].exp)
  45. {
  46. float t=(termarry[apos].coef)+(termarry[bpos].coef);
  47. c.newterm(t,termarry[apos].exp);
  48. apos++; bpos++;cpos++;
  49. }
  50. else if(termarry[apos].exp<b.termarry[bpos].exp)
  51. {
  52. c.newterm(b.termarry[bpos].coef,b.termarry[bpos].exp);
  53. bpos++;cpos++;
  54. }
  55. else
  56. {
  57. c.newterm(termarry[apos].coef,termarry[apos].exp);
  58. apos++;
  59. cpos++;
  60. }
  61. for(;apos<terms;apos++)
  62. {
  63. c.newterm(termarry[apos].coef,termarry[apos].exp);
  64. cpos++;
  65. }
  66. for(;bpos<b.terms;bpos++)
  67. {
  68. c.newterm(b.termarry[bpos].coef,b.termarry[bpos].exp);
  69. cpos++;
  70. }
  71. c.display(cpos);
  72. }
  73. void polynomial::display(int pos)
  74. {
  75. int i;
  76. for(i=0;i<pos;i++)
  77. {
  78. cout<<termarry[i].coef<<" "<<termarry[i].exp<<"+";
  79. }
  80. }
  81.  
  82. int main()
  83. {
  84. polynomial a,b;
  85. float coef1,coef2;
  86. int e1=0,e2=0,l1,l2;
  87. cout<<"Enter lowest deg: ";
  88. cin>>l1;
  89. cout<<"\nEnter first polynomial: ";
  90. while(1)
  91. {
  92. cin>>coef1>>e1;
  93. a.newterm(coef1,e1);
  94. if(e1==l1)
  95. break;
  96. }
  97. cout<<"Enter lowest deg: ";
  98. cin>>l2;
  99. cout<<"\nEnter second polynomial: ";
  100. while(1)
  101. {
  102. cin>>coef2>>e2;
  103. b.newterm(coef2,e2);
  104. if(e2==l2)
  105. break;
  106. }
  107. cout<<"\nPolynomial after addition: \n";
  108. a.add(b);
  109. return 0;
  110. }
Success #stdin #stdout 0s 2988KB
stdin
0
4 2
5 1
2 0
0
1 2
2 1
3 0
stdout
Enter lowest deg: 
Enter first polynomial: Enter lowest deg: 
Enter second polynomial: 
Polynomial after addition: 
0 2+2 1+3 0+2 1+3 0+