p9 C
p9 C
h>
#include <stdlib.h>
struct node {
int coeff;
int x_exp, y_exp, z_exp, z;
struct node *next;
};
struct node* insertTerm(int coeff, int x_exp, int y_exp, int z_exp, struct node
*poly);
void displayPolynomial(struct node *poly);
void evaluatePolynomial(int x, int y, int z, struct node *poly);
struct node* addPolynomials(struct node *poly1, struct node *poly2);
struct node* insertTerm(int coeff, int x_exp, int y_exp, int z_exp, struct node
*poly) {
struct node *newTerm = (struct node *)malloc(sizeof(struct node));
newTerm->coeff = coeff;
newTerm->x_exp = x_exp;
newTerm->y_exp = y_exp;
newTerm->z_exp = z_exp;
if (poly == NULL) {
poly = newTerm;
newTerm->next = poly;
} else {
struct node *temp = poly;
while (temp->next != poly) {
temp = temp->next;
}
temp->next = newTerm;
newTerm->next = poly;
}
return poly;
}
do {
polySum = insertTerm(temp1->coeff, temp1->x_exp, temp1->y_exp, temp1-
>z_exp, polySum);
temp1 = temp1->next;
} while (temp1 != poly1);
do {
struct node *search = polySum;
int found = 0;
do {
if (temp2->x_exp == search->x_exp && temp2->y_exp == search->y_exp &&
temp2->z_exp == search->z_exp) {
search->coeff += temp2->coeff;
found = 1;
break;
}
search = search->next;
} while (search != polySum);
if (!found) {
polySum = insertTerm(temp2->coeff, temp2->x_exp, temp2->y_exp, temp2-
>z_exp, polySum);
}
temp2 = temp2->next;
} while (temp2 != poly2);
return polySum;
}
int main() {
int choice, x, y, z;
struct node *poly2 = NULL;
poly1 = insertTerm(6, 2, 2, 1, poly1);
poly1 = insertTerm(-4, 0, 1, 5, poly1);
poly1 = insertTerm(3, 3, 1, 1, poly1);
while (1) {
printf("\nMenu:\n1. Display Polynomial P(x, y, z)\n2. Evaluate Polynomial
P(x, y, z)\n3. Add Polynomial P(x, y, z) to another Polynomial\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Polynomial P(x, y, z):\n");
displayPolynomial(poly1);
break;
case 2:
printf("Enter the values of x, y, z: ");
scanf("%d%d%d", &x, &y, &z);
evaluatePolynomial(x, y, z, poly1);
break;
case 3: {
poly2 = NULL;
printf("Inserting terms for POLY2\n");
poly2 = insertTerm(2, 1, 5, 1, poly2);
poly2 = insertTerm(-2, 1, 1, 3, poly2);
printf("POLY1:\n");
displayPolynomial(poly1);
printf("POLY2:\n");
displayPolynomial(poly2);
printf("POLYSUM:\n");
struct node* polySum = addPolynomials(poly1, poly2);
displayPolynomial(polySum);
break;
}
case 4:
exit(0);
}
}
}