Answer to Question #258208 in Algorithms for kanha

Question #258208

Write a C code to add two polynomials having two numbers of unknown variables


1
Expert's answer
2021-10-28T12:37:16-0400
#include<stdio.h>
#include<math.h>
#include<conio.h>


struct poly
{
	float coeff;
	int exp;
};


struct poly polynomial1[50],polynomial2[50],polynomialSum[50],d[50];


int main()
{
	int i;
	int d1,d2;  
	int k=0,l=0,m=0;
	printf("Enter the highest degree of polynomial 1: ");
	scanf("%d",&d1);
	for(i=0;i<=d1;i++){
		printf("Enter the coeff of x^%d :",i);
		scanf("%f",&polynomial1[i].coeff);
		polynomial1[k++].exp = i;
	}
	printf("Enter the highest degree of polynomial 2: ");
	scanf("%d",&d2);


	for(i=0;i<=d2;i++)
	{ 
		printf("Enter the coeff of x^%d: ",i);
		scanf("%f",&polynomial2[i].coeff);


		polynomial2[l++].exp = i;
	}


	printf("\nPolynomial 1 = %.1f",polynomial1[0].coeff);
	for(i=1;i<=d1;i++)
	{
		printf("+ %.1fx^%d",polynomial1[i].coeff,polynomial1[i].exp);
	}    


	printf("\nPolynomial 2 = %.1f",polynomial2[0].coeff);
	for(i=1;i<=d2;i++)
	{
		printf("+ %.1fx^%d",polynomial2[i].coeff,polynomial2[i].exp);
	}


	
	if(d1>d2)
	{
		for(i=0;i<=d2;i++)
		{
			polynomialSum[m].coeff = polynomial1[i].coeff + polynomial2[i].coeff;
			polynomialSum[m].exp = polynomial1[i].exp;
			m++;
		}


		for(i=d2+1;i<=d1;i++)
		{
			polynomialSum[m].coeff = polynomial1[i].coeff;
			polynomialSum[m].exp = polynomial1[i].exp;
			m++;
		}


	}
	else
	{
		for(i=0;i<=d1;i++)
		{
			polynomialSum[m].coeff = polynomial1[i].coeff + polynomial2[i].coeff;
			polynomialSum[m].exp = polynomial1[i].exp;
			m++;
		}


		for(i=d1+1;i<=d2;i++)
		{
			polynomialSum[m].coeff = polynomial2[i].coeff;
			polynomialSum[m].exp = polynomial2[i].exp;
			m++;
		}
	}




	printf("\nThe sum of the two polynomials = %.1f",polynomialSum[0].coeff);
	for(i=1;i<m;i++)
	{
		printf("+ %.1fx^%d",polynomialSum[i].coeff,polynomialSum[i].exp);
	}	 
	getchar();
	getchar();
	return 0;


}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS