Advertisement
ALENTL

Untitled

Aug 10th, 2024
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct {
  5. int coeff;
  6. int expo;
  7. } Poly;
  8.  
  9. int readPoly(Poly *p);
  10. int addPoly(Poly *p1, Poly *p2, Poly *p3, int t1, int t2);
  11. void displayPoly(Poly *p, int terms);
  12.  
  13. int main() {
  14. Poly *p1, *p2, *p3;
  15. int t1, t2, t3;
  16.  
  17. p1 = (Poly *)malloc(10 * sizeof(Poly));
  18. p2 = (Poly *)malloc(10 * sizeof(Poly));
  19. p3 = (Poly *)malloc(10 * sizeof(Poly));
  20.  
  21. printf("First Polynomial: \n");
  22. t1 = readPoly(p1);
  23. displayPoly(p1, t1);
  24.  
  25. printf("\nSecond Polynomial: \n");
  26. t2 = readPoly(p2);
  27. displayPoly(p2, t2);
  28.  
  29. printf("\nResultant Polynomial: \n");
  30. t3 = addPoly(p1, p2, p3, t1, t2);
  31. displayPoly(p3, t3);
  32. }
  33.  
  34. int readPoly(Poly *p) {
  35. int terms;
  36.  
  37. printf("Enter the number of terms: ");
  38. scanf("%d", &terms);
  39.  
  40. for (int i=0; i<terms; i++) {
  41. printf("Enter the coefficient: ");
  42. scanf("%d", &p[i].coeff);
  43. printf("Enter the exponent: ");
  44. scanf("%d", &p[i].expo);
  45. }
  46.  
  47. return terms;
  48. }
  49.  
  50. int addPoly(Poly *p1, Poly *p2, Poly *p3, int t1, int t2) {
  51. int i, j, k;
  52. i = j = k = 0;
  53.  
  54. while (i < t1 && j < t2) {
  55. if (p1[i].expo == p2[j].expo) {
  56. p3[k].expo = p1[i].expo;
  57. p3[k].coeff = p1[i].coeff + p2[j].coeff;
  58. i++, j++, k++;
  59. }
  60.  
  61. if (p1[i].expo > p2[j].expo) {
  62. p3[k].expo = p1[i].expo;
  63. p3[k].coeff = p1[i].coeff;
  64. i++, k++;
  65. }
  66.  
  67. if (p2[j].expo > p1[i].expo) {
  68. p3[k].expo = p2[j].expo;
  69. p3[k].coeff = p2[j].coeff;
  70. j++, k++;
  71. }
  72. }
  73.  
  74. while (i < t1) {
  75. p3[k].expo = p1[i].expo;
  76. p3[k].coeff = p1[i].coeff;
  77.  
  78. i++, k++;
  79. }
  80.  
  81. while (j < t2) {
  82. p3[k].expo = p2[j].expo;
  83. p3[k].coeff = p2[j].coeff;
  84.  
  85. j++, k++;
  86. }
  87.  
  88. return k;
  89. }
  90.  
  91.  
  92. void displayPoly(Poly *p, int terms) {
  93. int t;
  94. for (t=0; t<terms-1; t++) {
  95. printf("(%d)x^%d + ", p[t].coeff, p[t].expo);
  96. }
  97. printf("(%d)x^%d", p[t].coeff, p[t].expo);
  98. }
  99.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement