Slip 4 - B) Write a ‘C’ program to accept two polynomial and find the addition of accepted polynomials.(use array)

Solution:

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
    int a[20]={0},b[20]={0},c[20]={0},i,j,deg1,deg2,k;
    

    // 1st equation.

    printf("Enter degree of 1st polynomial equation : \n");
    scanf("%d",&deg1);
    printf("\nEnter your 1st equation (Coefficient only):\n");
    for(i=deg1;i>=0;i--)
    {
scanf("%d",&a[i]);
    }

    // 2nd equation.

    printf("\nEnter degree of 2nd polynomial equation : \n");
    scanf("%d",&deg2);
    printf("\nEnter your 2nd equation (Coefficient only):\n");
    for(j=deg2;j>=0;j--)
    {
scanf("%d",&b[j]);
    }

    // printing equations.

    printf("\n1st equation : ");
    for(i=deg1;i>=0;i--)
    {
if(a[i]>=0)
{
printf("+");
}
else
{
    printf("-");
}

printf("%dx^%d",abs(a[i]),i);
    }


    printf("\n\n2nd equation : ");
    for(j=deg2;j>=0;j--)
    {
if(b[j]>=0)
{
printf("+");
}
else
{
    printf("-");
}

printf("%dx^%d",abs(b[j]),j);
    }

    // addition of two equations
    i=j=k=0;
    if(deg1>deg2)
    {
while(i<=deg1)
{
c[k]=a[i]+b[j];
i++;
j++;
k++;
}

printf("\n\nResult of addition : ");
for(k=deg1;k>=0;k--)
{
if(c[k]>=0)
{
printf("+");
}
else
printf("-");

printf("%dx^%d",abs(c[k]),k);
}
    }
    else
    {
while(i<=deg2)
{
c[k]=b[j]+a[i];
i++;
j++;
k++;
}

printf("\n\nResult of addition : ");
for(k=deg2;k>=0;k--)
{
if(c[k]>=0)
{
printf("+");
}
else
printf("-");

printf("%dx^%d",abs(c[k]),k);
}
    }
    
}

Post a Comment

0 Comments