CH 2 Arrays and Structure
CH 2 Arrays and Structure
Arrays and
Structure
Introduction to Arrays
• Array is a collection of items of the same variable type that are
stored at contiguous memory locations. It is one of the most popular
and simple data structures used in programming.
• Basic terminologies of Array
• Array Index: In an array, elements are identified by their indexes.
Array index starts from 0.
• int arr[] = { 1, 2, 3, 4, 5 };
• char arr[5] = { 'a', 'b', 'c', 'd', 'e' };
• float arr[10] = { 1.4, 2.0, 24, 5.0, 0.0 };
Types of Arrays
3 2
-10 0
• Here, p[0][0] and p[0][1] are the coefficient and exponent respectively
of the first term.
• Another way to represent the polynomial is by using a structure. Each
term contains two parts coefficient and exponent. The structure for
term will be:
• struct poly{
• int coeff;
• int exp;
• };
• The polynomial contains more than one term. Hence, we
make an array of this structure.
• Struct poly p[3];
coeff exp
p[0] 7 4
p[1] 3 2
p[2] -10 0
• Here, p[0], p[1] and p[2] are the three terms. To access
the coefficient and exponent of each term, we use the
dot(.) operator.
• For example: p[0].coeff, p[0].exp and so on.
Polynomial Evaluation
• Polynomial evaluation means finding the value of the
polynomial by evaluating each term and finding the sum.
For example, the value of polynomial 7x4 + 3x²-10 if x=2 is
calculated as:
• 7*2+3*22-10=114.
• The algorithm to evaluate a polynomial in one variable is
given below:
Algorithm
1. Start
2. Accept n terms of polynomial p
3. Accept value of variable x
4. i=0, sum=0
5. while (i<n)
term_value = p[i].coeff* power(x,p[i].exponent)
sum = sum + term_value
i=i+1
6. Display sum
7.Stop
Addition of Polynomials
• Polynomial addition is one common operation performed
on polynomials. Two polynomials are added by adding
coefficients of terms having the same coefficient. For
example, addition of
• 7x4+3x²-10 and 5x3+6x²+4 is 7x4+5x3+9x²-6
• To add two polynomials, we have to compare the
exponents and add coefficients only if the exponents are
equal.
• Algorithm
1. Start
2. Accept m terms of polynomial p1 and n terms of p2
3. i=0, j=0, k=0;
4. while i<m and j<n
if(exponent of pl[i] = exponent of p2[j])
Add the two terms and store in p3[k]
Increment i, j, k
else
if(exponent of pl [i]> exponent of p2[j])
Copy term from p1[i] to p3[k]
Increment i, k
else
Copy term from p2[j] to p3[k]
Increment j, k
5. If (i<m)
Copy remaining terms from pl[i] to p3[k]
6. If (j<n)
Copy remaining terms from p2[j] to p3[k]
7. Display polynomial p3
8. Stop