Data Structures Practical 14
Question 1
Write a C program to Create a polynomial 5x4 + 3x2 + 1. Write a C program to display created polynomial.
poly.c
C
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct Node
{
int coeff;
int exp;
struct Node* next;
};
struct Node *start=NULL;
void insertTerm(int coeff, int exp)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->coeff = coeff;
newNode->exp = exp;
newNode->next = NULL;
if (start == NULL)
{
start=newNode;
return;
}
struct Node* temp = start;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = newNode;
}
void displayPolynomial()
{
struct Node* temp = start;
while (temp != NULL)
{
if (temp->exp == 0)
{
printf("%d", temp->coeff);
}
else if (temp->exp == 1)
{
printf("%dx", temp->coeff);
}
else
{
printf("%dx^%d", temp->coeff, temp->exp);
}
if (temp->next != NULL)
{
printf(" + ");
}
temp = temp->next;
}
printf("\n");
}
void main()
{
clrscr();
insertTerm(5, 4);
insertTerm(3, 2);
insertTerm(1, 0);
printf("The Polynomial is: ");
displayPolynomial();
getch();
}
Output
