Asked By: Pushkar Tiwari | C program to add two polynomials | Ask The Code
C Program to find the result of addition of two given polynomials by the user.
E.g., expr1 = 2x^3 + 3x^2 + 5x + 2 expr2 = 3x^3 + 2x^2 + 2x + 3 -------------------------------------------------------------------------
result = 5x^3 + 5x^2 + 7x + 5 Code:
/* C program to add two polynomials */
#include <stdio.h>
void display(int arr[], int n){
for(int i = n; i > 0; i--){
printf("%dx^%d + ",arr[i],i);
}
printf("%d ",arr[0]);
}
int main(){
int n;
printf("Enter the degree of the polynomial: ");
scanf("%d",&n);
int exp1[n], exp2[n], result[n];
printf("\nEnter the value for the first expression:\n");
for(int i = n; i >= 0; i--){
if(i == 0){
printf("Enter the constant in the polynomial: ");
}
else{
printf("Enter the coefficient of x^%d: ",i);
}
scanf("%d",&exp1[i]);
}
printf("\nEnter the value for the second expression:\n");
for(int i = n; i >= 0; i--){
if(i == 0){
printf("Enter the constant in the polynomial: ");
}
else{
printf("Enter the coefficient of x^%d: ",i);
}
scanf("%d",&exp2[i]);
}
printf("\nThe expressions are:\n");
display(exp1,n);
printf("\t...(i)");
printf("\n");
display(exp2,n);
printf(" \t...(ii)");
for(int i = n; i >= 0; i--){
result[i] = exp1[i] + exp2[i];
}
printf("\n-----------------------------------\n");
display(result,n);
printf("\t <- Result.");
return 0;
}
Commentaires