Addition of two Polynomials using Double Array

Exported from Notepad++
#include <stdio.h> #include <stdlib.h> #define MAX_TERMS 100 typedef struct { int coef; int expon; } POLY; POLY terms[MAX_TERMS]; int avail = 0; int compare ( int a, int b ) { if ( a < b ) return -1; if ( a == b ) return 0; return 1; } void attach ( int coefficient, int exponent ) { if ( avail >= MAX_TERMS ) { printf ( "\n Too many terms in the polynomial \n"); exit ( EXIT_FAILURE ); } terms[avail].coef = coefficient; terms[avail ++]. expon = exponent; } void padd ( int startA, int finishA, int startB, int finishB, int *startD, int *finishD ) { int coefficient; *startD = avail; while ( startA <= finishA && startB <= finishB ) { switch ( compare ( terms[startA].expon, terms[startB].expon ) ) { case - 1: attach ( terms[startB].coef, terms[startB].expon); startB ++; break; case 0: coefficient = terms[startA].coef + terms[startB].coef; if ( coefficient ) { attach( coefficient, terms[startA].expon); } startA ++; startB ++; break; case 1: attach ( terms[startA].coef, terms[startA].expon); startA ++; break; } } for ( ; startA <= finishA; startA ++ ) { attach ( terms[startA].coef, terms[startA].expon); } for ( ; startB <= finishB; startB ++ ) { attach ( terms[startB].coef, terms[startB].expon); } *finishD = avail - 1; } int main( void ) { int pTerms1, pTerms2; int startD, finishD; int i; printf ("\n polynomial Addition using Double Array"); printf ( "\n Enter Poly-1 terms: ?\b"); scanf ( "%d", &pTerms1 ); printf ( "\n Enter Poly-1: Coef Expon \n"); for ( i = 0; i < pTerms1; ++ i ) { scanf ("%d %d", &terms[i].coef, &terms[i].expon ); } printf ( "\n Enter Poly-2 terms: ?\b"); scanf ( "%d", &pTerms2 ); printf ( "\n Enter Poly-2: Coef Expon \n"); for ( i = i; i < ( pTerms1 + pTerms2 ); ++ i ) { scanf ("%d %d", &terms[i].coef, &terms[i].expon ); } avail = i; padd ( 0, pTerms1 - 1, pTerms1, pTerms1 + pTerms2, &startD, &finishD ); printf ( "\n Poly-1: \n"); for ( i = 0; i < pTerms1; ++ i ) { printf (" %dx^%d ", terms[i].coef, terms[i].expon ); } printf ( "\n Poly-2: \n"); for ( i = i; i < ( pTerms1 + pTerms2 ); ++ i ) { printf (" %dx^%d ", terms[i].coef, terms[i].expon ); } printf ( "\n Poly-3: \n"); for ( i = startD; i < finishD; ++ i ) { printf (" %dx^%d ", terms[i].coef, terms[i].expon ); } printf("\n\n"); } /* polynomial Addition using Double Array Enter Poly-1 terms: 2 Enter Poly-1: Coef Expon 2 1000 1 0 Enter Poly-2 terms: 4 Enter Poly-2: Coef Expon 1 4 10 3 3 2 1 0 Poly-1: 2x^1000 1x^0 Poly-2: 1x^4 10x^3 3x^2 1x^0 Poly-3: 2x^1000 1x^4 10x^3 3x^2 2x^0 */

No comments:

Post a Comment

Online Certifications

Python for Beginners Offered by: Christian Drumm, Stephan Jacobs Course dates: 2022-04-05 to 2022-06-01 Topics Python Fundamentals Lists and...