0% found this document useful (0 votes)
7 views35 pages

Unit 2

This document provides an introduction to algorithms, including specifications, recursive algorithms, and performance analysis through time and space complexity. It covers various data structures like arrays, polynomials, and strings, and explains the design and analysis of algorithms with examples of time complexity calculations. Additionally, it includes programming exercises for calculating factorials and GCD using both recursive and non-recursive methods, as well as an overview of the Fibonacci sequence and the Towers of Hanoi puzzle.

Uploaded by

Darth Vader
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views35 pages

Unit 2

This document provides an introduction to algorithms, including specifications, recursive algorithms, and performance analysis through time and space complexity. It covers various data structures like arrays, polynomials, and strings, and explains the design and analysis of algorithms with examples of time complexity calculations. Additionally, it includes programming exercises for calculating factorials and GCD using both recursive and non-recursive methods, as well as an overview of the Fibonacci sequence and the Towers of Hanoi puzzle.

Uploaded by

Darth Vader
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

UNIT 1

Algorithms: Introduction, Algorithm Specifications, Recursive Algorithms, Performance


Analysis of an algorithm- Time and Space Complexity, Asymptotic Notations.
Arrays: Arrays - ADT, Polynomials, Sparse matrices, Strings-ADT, Pattern Matching
==========================================================================

Algorithm-Specification
Def: An algorithm is a combination of, sequence of, finite number of steps to solve a problem.
Example
ATN()
{
1. Read two numbers;
2. Add the numbers and store the result in a variable
3. Print or write the result in a file.
}
Properties of an algorithm
1. Every algorithm must terminate after a finite number of steps.
Example: while(1)
{
Printf (“DSA”);
} //It is not an algorithm.
2. Every algorithm must produce some output.
3. Every algorithm may or may not take some input.
4. Every statement in algorithm must be effective.
Example: x = x; // waste of CPU time. So, not an effective statement.
5. Every algorithm must be deterministic.
6. Algorithm is independent of programming language.

Step to design algorithm


1. Problem statement | Problem definition |Knowing the problem

2. Select the design technique

3. Draft flow chart


4. Implementation or coding
5. Verification | testing
6. Analysis  The better one.

DR. V SREENIVASULU 1
Better: If a problem has more than one algorithm, one the better one is selected. How to find
the better one?  Two metrics 1. Time 2. Space
Time Complexity: Time taken by the CPU to run the algorithm should be less.
Space Complexity: Space (memory) needs to run the algorithm should be less.
Time Complexity

Analysis
Aposteriori Apriori
1 It can also be called as Relative 1 It can also be called as absolute
analysis analysis
2 It is dependent on compiler and 2 It is independent on compiler and
processor processor
3 It gives more realistic analysis 3 It gives approximate analysis
4 Analysis change from system to 4 No change of analysis irrespective of
system any system

Apriori Analysis: It determines the order of magnitude of statements

Algorithm A
I3  100ns O(1)
I5  10ns O(1)
I7  2ns O(1)
Super Computer  ns/100 Log(n)

DR. V SREENIVASULU 2
Exercise: Finding Time complexity for the given problems
1. main()
{
x = y + z;
}
T.C  (1)  order of magnitude  O(1) or Ω(1) or Θ(1)
----------------------------------------------------------------------------------------------------------------
2. Find out the time complexity of the given snippet
main()
{
x = y + z;
a = b + c;
p = q + r;
r = s + t;
}
T.C  4ns  O(1)  ignore constant
----------------------------------------------------------------------------------------------------------------
3. Find out the time complexity of the given snippet
main()
{
x = y + z;
for( i = 0; i < n; i++ )
p = q + r;
r = s + t;
}
T.C  1 + n + n - 1 + 1 = 2n + 1  O(n)  approximation
----------------------------------------------------------------------------------------------------------------
4. Find out the time complexity of the given snippet
main()
{
x = y + z;
for( i = 0; i < n; i++ )
p = q + r;
for( i = 0; i < n; i++ )
r = s + t;
}
T.C  1 + n + n -1 + n + n - 1 = 4n - 1  O(n)  approximation
----------------------------------------------------------------------------------------------------------------

DR. V SREENIVASULU 3
5. Find out the time complexity of the given snippet
main()
{
x = y + z;
for( i = 0; i < n; i++ )
p = q + r;
for( i = 0; i < n; i++ )
for( j = 0; j < n; j++ )
r = s + t;
}
T.C  = O(n2)  approximation
----------------------------------------------------------------------------------------------------------------
6. Find out the time complexity of the given snippet
main()
{
for( i = 0; i < n/2; i++ )
for( j = 0; j < n/2; j++ )
r = s + t;
}
T.C  = O(n2)  approximation
----------------------------------------------------------------------------------------------------------------
7. Find out the time complexity of the given snippet
main()
{
for( i = 0; i < n2; i++ )
for( j = 0; j < n2; j++ )
r = s + t;
}
T.C  = O(n2)  approximation
----------------------------------------------------------------------------------------------------------------
--
8. Find out the time complexity of the given snippet
main()
{
i = 1;
while(i < n )
{
i = i + 1;
}

DR. V SREENIVASULU 4
}
T.C  = 1 + n + n – 1 = 2n O(n)  approximation
----------------------------------------------------------------------------------------------------------------
9. Find out the time complexity of the given snippet
main()
{
i = 1;
while(i < n )
{
i = i + 2;
i = i + 18;
i = i – 5;
}
}
T.C  = 1 + 20 – 5 = n . 1/15  1/15 is constant. So, O(n)  approximation
----------------------------------------------------------------------------------------------------------------
10. Find out the time complexity of the given snippet
main()
{
i = n;
while(i > 1 )
{
i = i + 2;

}
}
T.C  = n is already bigger. Again incrementing by 2. Violating algorithm properties.
----------------------------------------------------------------------------------------------------------------
11. Find out the time complexity of the given snippet
main()
{
i = 1;
while(i > 1 )
{
i = i * 2;

}
}
T.C  = (log2n)

DR. V SREENIVASULU 5
12. Find out the time complexity of the given snippet
main()
{
i = 1;
while(i > 1 )
{
i = i * 20;
i = i/20;
i = i/5;
}
}
T.C  = (log n)
----------------------------------------------------------------------------------------------------------------
13. Find out the time complexity of the given snippet
main()
{
i = 1;
while(i > 1 )
{
i = i * 2;

}
}
T.C  = (log2n)
----------------------------------------------------------------------------------------------------------------
14. Find out the time complexity of the given snippet
main()
{
i = 1;
while(i > 1 )
{
i = i2;

}
}
T.C  = (log2log2n)
----------------------------------------------------------------------------------------------------------------

DR. V SREENIVASULU 6
15. Find out the time complexity of the given snippet
main()
{
i = 5;
while(i > 1 )
{
i = i7;

}
}
T.C  = (log7log5 n)
----------------------------------------------------------------------------------------------------------------

Recursion
1. A function is calling itself with the same code to solve a problem is termed as
recursion.
2. Solving a big problem in terms of a small problems. Call first, completed last  stack.
3. A stack is used to execute recursive program,
n * fact (n – 1)
n * fact (n – 1)
n * fact (n – 1)
n * fact (n – 1)
n * fact (n – 1)
n * fact (n – 1)

4. For every recursive Program, there exists a non-recursive Program.


Recursive Program non- Recursive Program

1 Function name, parameters are 1 Function name, parameters are different


same
2 Function definition is the same 2 Function definition is different

3 Base condition exists 3 Loop/Loops exists

4 Easy for programmer and 4 Easy for the CPU but complex for the
complex for the CPU programmer.

DR. V SREENIVASULU 7
5. Algorithms

Recursive Algorithm non- Recursive Algorithm


int fact(int n) int fact(int n)
{ {
if(n == 1) // base condition int f = 1, i;
return 1; for(i = n; i > 1; i--)
else f = f * i;
return n * fact (n – 1); return f;
} }

6. Base Condition: Function call is a push operation. If no base condition, it pushes and
pushes till internal “Stack overflows”. Displays error message  run time error.
7. Comparing RP and NRP, RP takes more memory space. # stack units are used in RP.
Factorial Computation
The factorial of a number n, denoted as n!, is the product of all positive integers less than or
equal to n. Mathematically, it is defined as

Example: 5! = 5 X 4 X 3 X 2 X 1 = 120
Recursive Definition of Factorial
In recursion, a function calls itself with a smaller argument until it reaches a base case. The
factorial function can be defined recursively as

 Base case: The factorial of 0 or 1 is 1.


 Recursive case: The factorial of any number n>1 is n×(n−1)!.

DR. V SREENIVASULU 8
1_Write a C Program that reads a number and find out the factorial for that number
using non-recursion
#include<stdio.h>

int fact(int);
int main()
{
int num;
printf ("Enter a number...");
scanf ("%d", &num);

fact(num);
return 0;
}

int fact (int n)


{
int i, fact = 1;

for(i = n; i > 0; i--)


{
fact = fact * i;
}

printf ("Factorial of %d is ...%d\n", n, fact);


}

OUTPUT
Case1:
Enter a number...5
Factorial of 5 is ...120

Case 2:
Enter a number...6
Factorial of 6 is ...720

DR. V SREENIVASULU 9
2_Write a C Program that reads a number and find out factorial for that number using
recursion
#include<stdio.h>
int fact(int n);
int main()
{
int num, f(int), factorial;
printf ("Enter a number...");
scanf ("%d",&num);
factorial = fact(num);
printf ("Factorial of %d is ...%d\n", num, factorial);
return 0;
}
int fact (int n)
{
if(n == 0)
return 1;
else
return (n * fact(n-1));
}

OUTPUT
Case1:
Enter a number...5
Factorial of 5 is ...120

Case 2:
Enter a number...6
Factorial of 6 is ...720

DR. V SREENIVASULU 10
3_Write a C Program that reads any two numbers and finds the GCD of for that two
numbers using non-recursion

#include <stdio.h>

int gcd (int a, int b)


{
While (a != b)
{
if ( a > b)
a = a - b;
else b = b - a;
}
return b;
}
int main ()
{
int num1, num2;

printf ("Enter two integers: ");


scanf ("%d %d", &num1, &num2);

printf ("GCD of %d and %d is: %d\n", num1, num2, gcd(num1, num2));

return 0;
}

OUTPUT
Case1:
Enter two integers: 24 18
GCD of 24 and 18 is: 6

Case2:
Enter two integers: 24 36
GCD of 24 and 36 is: 12

DR. V SREENIVASULU 11
4_Write a C Program that reads any two numbers and finds the GCD of for that two
numbers using recursion

#include<stdio.h>

void main ()
{
int num1, num2, gcd;
printf ("Enter two numbers ...");
scanf ("%d %d", &num1,&num2);

gcd = GCD(num1, num2);

printf ("GCD of %d, %d is %d",num1,num2,gcd);


}

int GCD(int n1, int n2)


{
if(n2 == 0)
return n1;
else
return GCD(n2,n1%n2);

OUTPUT

Case1:
Enter two numbers ...50 24
GCD of 50, 24 is 2

Case2:
Enter two numbers ...36 18
GCD of 36, 18 is 18

DR. V SREENIVASULU 12
Fibonacci Sequence
Fibonacci sequence is a series of numbers in which each number is the sum of the previous
two numbers usually starting with 0 and 1.

The sequence looks like this:


0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...

Mathematically, it is defined by the recurrence relation


F(n) = F(n−1) + F(n−2)
Where:
 F (0) = 0 (the first term)
 F (1) =1 (the second term)
 For n ≥ 2, F(n) is the sum of the previous two terms.

This sequence appears in various applications.

5_Write a C Program that prints Fibonacci sequence of numbers using recursion

#include <stdio.h>

int fibonacci (int n)


{
if (n <= 1)
return n;
else
return fibonacci (n - 1) + fibonacci (n - 2);
}
int main ()
{
int num, i;

printf ("Enter the number of terms… ");


scanf ("%d", &num);

printf ("Fibonacci sequence…. ");

for (i = 0; i < num; i++)


{
printf ("%d ", fibonacci(i));
}

return 0;
}

DR. V SREENIVASULU 13
OUTPUT
Case 1
Enter the number of terms: 8
Fibonacci sequence: 0 1 1 2 3 5 8 13

Case 2
Enter the number of terms: 9
Fibonacci sequence: 0 1 1 2 3 5 8 13 21

Towers Of Hanoi
The Towers of Hanoi is a mathematical puzzle involving three pegs and a set of disks of
different sizes. The puzzle starts with all the disks in descending order of size with the largest
disk at the bottom and the smallest disk at the top.
Objective
The goal is to move all the disks from the source peg to another peg with these rules:
1. Only one disk can be moved at a time.
2. A disk can only be moved to the top of another peg.
3. No larger disk can be placed on top of a smaller disk.
Recursive Approach
Recursive can be used to solve the Towers of Hanoi puzzle. For n disks, the solution involves
as given below.

Steps to Solve The Towers of Hanoi


1. Move n-1 disks from the source peg to the auxiliary peg using the destination peg.
2. Move the nth (largest) disk directly from the source peg to the destination peg.
3. Move the n-1 disks from the auxiliary peg to the destination using the source peg.
Recursive Formula
If we have n disks, the minimum number of moves required to solve the problem is:
T(n) = 2n - 1 Where T(n) is the total number of moves and n is the number of disks.

DR. V SREENIVASULU 14
6_Write a C Program that uses Recursive Algorithm for Solving the Towers of Hanoi
Problem

#include <stdio.h>

void shiftDisk(int n, char source, char aux, char des) // Function to move disks
{
if (n == 1)
{
printf ("Shift disk 1 source %c Destination %c\n", source, des);
return;
}

shiftDisk(n - 1, source, des, aux); // Shift n-1 disks from the source to auxiliary

printf ("Shift disk %d source %c destination %c\n", n, source, des);

shiftDisk(n - 1, aux, source, des); // Shift the n-1 disks from auxiliary to destination
}
int main()
{
int n,i;

printf ("Enter the number of disks...");


scanf ("%d", &n);

printf ("\nDisks on Source Peg S\n"); // Displaying initial state of the source peg

for (i = n; i >= 1; i--)


{
printf ("Disk %d\n",i);
}
printf ("\n");

shiftDisk(n, 'S', 'A', 'D');// Function call

printf ("\nDisks on the destination Peg D\n");


for (i = n; i >= 1; i--)
{
printf ("Disk %d\n", i);
}
return 0;
}

DR. V SREENIVASULU 15
OUTPUT
Enter the number of disks...3

Initial State
Post A
Disk 3
Disk 2
Disk 1

Shift disk 1 from_Post A to_Post C


Shift disk 2 from_Post A to_Post B
Shift disk 1 from_Post C to_Post B
Shift disk 3 from_Post A to_Post C
Shift disk 1 from_Post B to_Post A
Shift disk 2 from_Post B to_Post C
Shift disk 1 from_Post A to_Post C

Disks on the destination Post C


Disk 3
Disk 2
Disk 1

Array Abstract Data Type (ADT)


The Array Abstract Data Type (ADT) is a collection of elements of the same data type, stored
in a contiguous block of memory. Each element in an array can be accessed using an index,
which allows for efficient retrieval, insertion, and manipulation of data.

Arrays Properties of an Array

Fixed Size: Arrays have a predetermined size once they are created. In many languages,
Change the size of an array is not possible after its declaration.

Indexed Access: Elements can be accessed directly using an index. Indexing starts at 0 in
most programming languages.

Homogeneous Elements: All elements in an array are of the same data type.

Contiguous Memory Allocation: Elements are stored in a contiguous block of memory,


allowing efficient access.

DR. V SREENIVASULU 16
Common Operations in Array ADT
Access: Retrieve an element at a given index.
Example: array[i]

Update: Modify the value of an element at a particular index.


Example: array[i] = value

Traversal: Visit all elements of the array in sequence.


Example: for element in array:
Insertion: Add a new element only at the end in fixed-size arrays or after shifting elements
in dynamic arrays.
Example: array. append(value) (Python list)

Deletion: Remove an element from the array.


Example: del array[i] or array. remove(value)

Search: Find the position of a particular element in the array.


Example: array. index(value)

Sorting: Arrange the elements in a specific order (e.g., ascending or descending).


Example: sorted(array)

Length: Get the number of elements in the array.


Example: len(array)

Definition of Arrays

An array is a data structure that stores a collection of elements, all of the same type, in a
contiguous block of memory. Arrays allow to store multiple values under a single variable
name and access them using an index.

Properties of Arrays

1. Fixed Size: Once an array is created, its size is fixed and cannot be changed. This is
why  specify the size when creating an array.

2. Same Data Type: All elements in an array must be of the same data type, such as
integers, floats, or strings.

3. Zero-Indexed: In most programming languages, arrays are indexed starting from 0.


This means the first element is at index 0, the second at index 1, and so on.

DR. V SREENIVASULU 17
Advantages of Arrays
Efficiency: Arrays provide constant-time access to elements using their index.
Compactness: Arrays store elements in a contiguous block of memory, reducing
overhead.
Limitations of an array
Fixed Size: Arrays have a fixed size, so First of all give the size of the array. It leads to
some other problems  over size and below size.
Same Data Type: Arrays can only hold elements of a single data type.

Initialization of 1D Array
Full Initialization: int arr[5] = {10, 20, 30, 40, 50};
Partial Initialization: int arr [5] = {1, 2}; // Rest are set to 0
Implicit Size: int arr [] = {10, 20, 30}; // Size is automatically set to 3
All Zeros: int arr [5] = {0}; // All elements are initialized to 0
Dynamic Assignment: Declare first, then assign using indices: arr[0] = 10;

7_Write a C Program that performs Array initialization, reading and printing the
elements
#include <stdio.h>

int main()
{
int n, i;

printf ("Enter the number of elements... ");


scanf ("%d", &n);

int intArray[n];
char charArray[n];
double doubleArray[n];

printf ("Enter %d integers...", n); // Reading integers from the user


for (i = 0; i < n; i++)
{
scanf ("%d", &intArray[i]);
}

printf ("\nEnter %d characters...", n); // Reading characters from the user


for (i = 0; i < n; i++)
{
scanf (" %c", &charArray[i]); // Space before %c to skip any newline or whitespace
}

DR. V SREENIVASULU 18
printf ("\nEnter %d doubles...", n);
for (i = 0; i < n; i++)
{
scanf ("%lf", &doubleArray[i]);
}

printf ("\nElements in the integers array\n");


for (i = 0; i < n; i++)
{
printf ("Integer[%d]: %d\n", i, intArray[i]);
}

printf ("\nElements in the characters array\n");


for (i = 0; i < n; i++)
{
printf ("Character[%d]: %c\n", i, charArray[i]);
}

printf ("\nElements in the doubles array\n");


for (i = 0; i < n; i++)
{
printf ("Double[%d]: %.2lf\n", i, doubleArray[i]); // "%.2lf" limits to 2 decimal places
}

return 0;
}

OUTPUT
Enter the number of elements... 3
Enter 3 integers...1 2 3

Enter 3 characters...A B C
Enter 3 doubles...1.2 2.3 3.4

Elements in the integers array


Integer[0]: 1
Integer[1]: 2
Integer[2]: 3

DR. V SREENIVASULU 19
Elements in the characters array
Character[0]: A
Character[1]: B
Character[2]: C

Elements in the doubles array


Double[0]: 1.20
Double[1]: 2.30
Double[2]: 3.40

2D array
A 2D array (two-dimensional array) is an array of arrays, where data is stored in a table-like
structure with rows and columns. Each element in a 2D array is accessed using two indices:
one for the row and one for the column.

Table Structure: A 2D array is like a table with rows and columns. For example, a 3x3 matrix
has 3 rows and 3 columns.
Two Indices: Elements are accessed elements using two indices. The first index represents
the row and the second index represents the column.

Fixed Size: The size of a 2D array is fixed so size must be specified both the number of rows
and columns when declaring it.

Same Data Type: All elements in the array must be of the same data type (e.g., all integers,
all doubles, etc.).

Syntax of 2D Array in C
data_type array_name[rows][columns];

Where

data_type is the type of elements (e.g., int, float, char).


array_name is the name of the array.
rows is the number of rows.
columns is the number of columns.

DR. V SREENIVASULU 20
8_Write a C Program that reads elements for two 2D arrays, add element to element
and display the resultant array

#include <stdio.h>

int main()
{
int rows, columns, i, j;

printf ("Enter the number of rows and columns... ");


scanf ("%d %d", &rows, &columns);

int array1[rows][columns], array2[rows][columns], sumArray[rows][columns];

printf ("Enter the elements of the first array...");


for (i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
{
scanf ("%d", &array1[i][j]);
}
}

printf ("Enter the elements of the second array...");


for (i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
{
scanf ("%d", &array2[i][j]);
}
}

for (i = 0; i < rows; i++)


{
for (j = 0; j < columns; j++)
{
sumArray[i][j] = array1[i][j] + array2[i][j];
}
}

printf ("\nThe sum of the two arrays is:\n");

DR. V SREENIVASULU 21
for (i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
{
printf ("%d ", sumArray[i][j]);
}
printf ("\n");
}

return 0;
}

OUTPUT

Enter the number of rows and columns... 3 3


Enter the elements of the first array...1 2 3 4 5 6 7 8 9
Enter the elements of the second array...9 8 7 6 5 4 3 2 1

The sum of the two arrays is:


10 10 10
10 10 10
10 10 10
Polynomials
Definition: Polynomial representation of an array is a mathematical expression where
 The elements of an array are treated as coefficient, variable and exponent of a
polynomial.
 Ex1: 3x2 + 6x + 5
 Index of the element determines the power of the variable in the term.
 Degree of the polynomial (3) = 3 – 1 = 2.
 First term is 3x2  3 is coefficient, x is variable and 2 is an exponent.
 Second term is 6x  6 is coefficient x is variable and 1 is exponent.
 Third is 5 (x is absent)  5 is coefficient and 0 is exponent.
----------------------------------------------------------------------------------------------------------------
Ex2: 6x3+7x2+6
 Degree of the polynomial (3) = 4 – 1 = 3.
 First term is 6x3  6 is coefficient x is variable and 3 is an exponent.
 Second term is 7x2  7 is coefficient x is variable and 2 is exponent.
 Third term is (x is absent)  0 is coefficient and 1 is exponent.
 Fourth term is  6 coefficient x is variable and exponent 0.
----------------------------------------------------------------------------------------------------------------

DR. V SREENIVASULU 22
Array representation of polynomial
Example  4x5 + 3 x3 + 2 x2 + 5x + 2

To represent the above example using array of structures


Term 1 Term 2 Term 3 Term 4 Term 5

4 5 3 3 2 2 5 1 2 0

P[0] P[1] P[2] P[3] P[4]

struct Poly
{
int coeff;
int exp;
} p[20];
Algorithm
1. Declare an array of structure.
2. Read the number of terms from the keyboard.
3. The number of terms of the polynomial indicates, the number of elements in the array.
4. Use a loop to read the coefficient and exponent of each term of the polynomial.
5. The term should be in the descending order of their exponents.
6. Display the polynomial.

Addition of polynomials

A (x) = 4x5 + 3 x3 + 2 x2 + 5x + 2

Term 1 Term 2 Term 3 Term 4 Term 5

4 5 3 3 2 2 5 1 2 0

p[0] p[1] p[2] p[3] p[4]

B (x) = 6x5 + 4x4 + 7 x2 + 8x

Term 1 Term 2 Term 3 Term 4

6 5 4 4 7 2 8 1

q[0] q[1] q[2] q[3]

DR. V SREENIVASULU 23
A (x) + B (x) = 10x5 +4x4 + 3 x3 + 9 x2 + 13x + 2

Term 1 Term 2 Term 3 Term 4 Term 5 Term 6

10 5 4 4 3 3 9 2 13 1 2 0

r[0] r[1] r[2] r[3] r[4] r[5]

Algorithm for Addition of two polynomials


 Read the two polynomials and store them using array of structures. The terms should
be in the descending order of their exponents.
 Declare an array for storing the resultant polynomial.
 Traverse the arrays until one of them gets exhausted.
 Use 3 separate indices to traverse the 3 arrays.
 Compare the exponents of each of the terms of the two polynomials.
 Check the three cases

Case 1: Exponent of a term in first polynomial > exponent of a term in second


polynomial.
Copy the coefficient and exponent of the greater term to the resultant
polynomial and advance the index of the first polynomial to the next term and
advance resultant polynomial.

Case 2: Exponent of a term in first polynomial == exponent of a term in second


polynomial.
Add the coefficients of the both the terms and pass the sum to the resultant
Polynomial.
Advance all the indices to the next term of all the polynomials.

Case 3: Exponent of the term in first polynomial < exponent of the term in second
Polynomial
Copy the coefficient and exponent of the greater term to the resultant
polynomial and advance the index of the second polynomial to the next term
and also advance the index
If one of the polynomials gets exhausted copy the remaining terms of the other
polynomial into the resultant polynomial.
Print the resultant polynomial.
Note: Other operations include polynomial subtraction and Multiplication.

DR. V SREENIVASULU 24
9_Write a C Program for Adding Two Polynomials of Different Degrees Using Arrays
to Represent Coefficients for addition of two polynomials and display the Output

#include <stdio.h>

void addPolynomials (int poly1[], int deg1, int poly2[], int deg2, int result [])
{
int i;
int maxDegree = (deg1 > deg2) ? deg1 : deg2;

for (i = 0; i <= maxDegree; i++)


{
if (i <= deg1 && i <= deg2) //Adding coeffients
result[i] = poly1[i] + poly2[i];
else if (i <= deg1)
result[i] = poly1[i];
else
result[i] = poly2[i];
}
}

int main ()
{
int i, degree1, degree2;

printf ("Enter degree of first polynomial ... ");


scanf ("%d", &degree1);
int poly1[degree1 + 1]; // Array to store coefficients of first polynomial

printf ("Enter coefficients of first polynomial from highest to lowest degree\n");


for (i = degree1; i >= 0; i--)
{
printf ("Coefficient of x^%d: ", i);
scanf ("%d", &poly1[i]);
}

printf ("Enter degree of second polynomial: ");


scanf ("%d", &degree2);
int poly2[degree2 + 1]; // Array to store coefficients of second polynomial

printf ("Enter coefficients of second polynomial from highest to lowest degree)\n");

DR. V SREENIVASULU 25
for (i = degree2; i >= 0; i--)
{
printf ("Coefficient of x^%d: ", i);
scanf ("%d", &poly2[i]);
}

int maxDegree = (degree1 > degree2) ? degree1 : degree2;


int result[maxDegree + 1]; // Array to store the result polynomial

addPolynomials (poly1, degree1, poly2, degree2, result);// Adding two polynomials

printf ("Resultant polynomial after addition ");


for (i = maxDegree; i >= 0; i--)
{
if (result[i] != 0)
{
printf ("%d", result[i]);
if (i > 0)
printf ("x^%d ", i);
if (i > 0 && result[i - 1] > 0)
printf ("+ ");
}
}
printf ("\n");

return 0;
}

OUTPUT
Case 1
Enter degree of first polynomial ... 3
Enter coefficients of first polynomial from highest to lowest degree
Coefficient of x^3: 2
Coefficient of x^2: 0
Coefficient of x^1: 3
Coefficient of x^0: 4

Enter degree of second polynomial: 2


Enter coefficients of second polynomial from highest to lowest degree)
Coefficient of x^2: 1
Coefficient of x^1: 5
Coefficient of x^0: 7
Resultant polynomial after addition 2x^3 + 1x^2 + 8x^1 + 11

DR. V SREENIVASULU 26
Case 2
Enter degree of first polynomial ... 4
Enter coefficients of first polynomial from highest to lowest degree
Coefficient of x^4: 2
Coefficient of x^3: 3
Coefficient of x^2: 0
Coefficient of x^1: 0
Coefficient of x^0: 4
Enter degree of second polynomial: 3
Enter coefficients of second polynomial from highest to lowest degree)
Coefficient of x^3: 1
Coefficient of x^2: 7
Coefficient of x^1: 0
Coefficient of x^0: 5
Resultant polynomial after addition 2x^4 + 4x^3 + 7x^2 9

Sparse Matrix
Sparse are those matrices that have more number of zeros than non-zero elements.

0 0 1
Sparse Matrix S = 0 7 0 3X3 matix
0 8 0

Disadvantages of Sparse Matrix:

 Representing a Sparse Matrix by 2D array causes wastage of memory as storing zeros.


 There is no use of zero elements.
 Storage zero elements take more space.
 Reaching the non-zero element by crossing zero elements takes more CPU time.

Remedy: Instead of storing zeros, better to store only non-zero elements in triple matrix
without changing the location.

Sparse matrix representation can be done most commonly in two types.


1. Array Representation 2. Linked List Representation.

DR. V SREENIVASULU 27
0 0 1 0

7 0 0 0
Sparse Matrix S-
0 8 1 0

4 0 0 2

Array representation of Sparse matrix

0 0 1 0 7 0 0 0 0 8 1 0 4 0 0 2

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Array representation of Trple Matrix

Row Col Val


4 4 6
0 2 1
1 0 7
2 1 8
2 2 1
3 0 4
3 3 2

10_Write a C Program that implements Sparse Matrix into a Triple Matrix

#include <stdio.h>

#define MAX 10

void sparseToTriple(int sparse[MAX][MAX], int rows, int cols)


{
int triple [MAX][3]; int i, j, k = 0;

for (i = 0; i < rows; i++)


{

DR. V SREENIVASULU 28
for (j = 0; j < cols; j++)
{
if (sparse [i][j] != 0)
{
triple [k][0] = i;
triple [k][1] = j;
triple [k][2] = sparse[i][j];
k++;
}
}
}

printf ("Triple Matrix (row, column, value):\n");


printf ("Row\tColumn\tValue\n");
for (i = 0; i < k; i++)
{
printf ("%d\t%d\t%d\n", triple[i][0], triple[i][1], triple[i][2]);
}
}

int main()
{
int sparse[MAX][MAX], i, j, rows, cols;

printf ("Enter the number of rows and columns of the sparse matrix... ");
scanf ("%d %d", &rows, &cols);

printf ("Enter the elements of the sparse matrix\n");


for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
scanf ("%d", &sparse[i][j]);
}
}
sparseToTriple (sparse, rows, cols); //fn call

return 0;
}

DR. V SREENIVASULU 29
OUTPUT
Case 1
Enter the number of rows and columns of the sparse matrix: 4 4
Enter the elements of the sparse matrix:
0010700008104002
Triple Matrix (row, column, value):
Row Column Value
0 2 1
1 0 7
2 1 8
2 2 1
3 0 4
3 3 2

Case 2
Enter the number of rows and columns of the sparse matrix: 6 5
Enter the elements of the sparse matrix:
000070040001005200000800001002
Triple Matrix (row, column, value):
Row Column Value
0 4 7
1 2 4
2 1 1
2 4 5
3 0 2
4 1 8
5 1 1
5 4 2

String Abstract Data Type (ADT)


A String Abstract Data Type (ADT) refers to a data structure that stores and manipulates
sequences of characters. It is commonly used in programming languages to represent text.
The String ADT supports a variety of operations that enable efficient handling of text data.

Common Operations in String ADT

Concatenation: Combining two or more strings into one.


Example: "Hello" + " World" = "Hello World"

Length: Finding the number of characters in a string.


Example: len("Hello") = 5

DR. V SREENIVASULU 30
Indexing: Accessing a specific character in a string by its position.
Example: "Hello"[1] = 'e' (index starts at 0)

Slicing: Extracting a substring from the string.


Example: "Hello"[1:4] = "ell" (from index 1 to 3)

Searching: Finding the position of a substring within a string.


Example: "Hello". find ("e") = 1

Comparison: Comparing two strings lexicographically.


Example: "apple" < "banana" = True

Substring Checking: Checking if a string contains another string.


Example: "Hello" in "Hello World" = True

Replace: Replacing a substring with another string.


Example: "Hello World".replace ("World", "C Language") = "Hello C Language"

Splitting: Dividing a string into a list of substrings based on a delimiter.


Example: "Hello World".split(" ") = ['Hello', 'World']

Joining: Combining elements of a list into a string with a delimiter.


Example: "-".join(['Hello', 'World']) = 'Hello-World'

Conversion to Upper/Lower Case:


Example: "hello".upper() = "HELLO", "HELLO".lower() = "hello"

11_Write a C Program that perform all String functions

#include <stdio.h>
#include <string.h>

int main()
{
int i;
char str1[50];// = " PS students ";
char str2[50];// = "Learning DSA";
printf("Enter a string...");
scanf("%s",str1);
printf("Enter another string...");

DR. V SREENIVASULU 31
scanf("%s",str2);

strcat(str1, str2);
printf("Concatenated String: %s\n", str1);

printf("Length of str1: %lu\n", strlen(str1));

char str3[50];
strcpy(str3, str1);
printf("Copied String: %s\n", str3);

if (strcmp(str1, str3) == 0)
{
printf("str1 and str3 are equal\n");
}

char *pos = strstr(str1, "C Programming");


if (pos)
{
printf("Substring found: %s\n", pos);
}

int len = strlen(str3); // Reversing str3


for (i = 0; i < len / 2; i++)
{
char temp = str3[i];
str3[i] = str3[len - i - 1];
str3[len - i - 1] = temp;
}
printf("Reversed String: %s\n", str3);

return 0;
}

OUTPUT
Enter a string...Hyderabad
Enter another string...Khammam
Concatenated String: HyderabadKhammam
Length of str1: 16
Copied String: HyderabadKhammam
str1 and str3 are equal
Reversed String: mammahKdabaredyH

DR. V SREENIVASULU 32
Pattern Matching
 Pattern matching is done using string manipulation functions.
 A given pattern is verified in the string that is embedded in it or not.
Ex: Text [0…n-1]

Pattern [0…m-1]
For verification, we use different algorithms.
 Brute force algorithm is the basic algorithm.
Brute Force Algorithm
Requirements  1. Two strings i) text ii) pattern

Procedure
 The first character of the text is compared with the pattern.
 If both characters match then compare the second character of the text with the second
character of the pattern. If matched, go to third character. It repeats till the end of the
pattern.
 Then, it is declared that the pattern is available. Then no need to compare the
remaining text.
 Stop the iteration. Otherwise, declare that the pattern is not available.

Text  a b b b a b a b a a b

Pattern  a b a A

DR. V SREENIVASULU 33
Algorithm-Brute Force (t (0 ..n-1, p(0…m-1))
{
m = strlen (p);
n = strlen (t);
for (i = 0; i <= n - m; i++)
{
for ( j = 0; j < m; j++)
{
if (t(i + j) != p(j))
break;
}
if (j==m) return i;
}
}
Procedure:
1. Compare the first symbol of the text with the first symbol of the pattern. If both
are equal move i to next location of the text.
2. Again, the second symbol of the text is compared with the pattern. Since, it is
equal, move i to the next location of the text.
3. Third symbol mismatches. If mismatch occurs, shift the pattern one cell to the
right and backtracks the variable i.

12_Write a C Program that Implements String Pattern Matching

#include <stdio.h>
#include<string.h>

int patternMatch(char t[], char p[])


{
int i,j;
int n = strlen(t);
int m = strlen(p);

for (i = 0; i < n-m; i++)


{
for (j = 0; j < m; j++)
{
if (t[i+j] != p[j])
break;
}

DR. V SREENIVASULU 34
if (j == m)
{
return i;
}
}
return -1;
}

int main()
{
char text[100], pattern[50];

printf("Enter a lengthy string... ");


scanf ("%s", text);

printf("Enter the pattern to search... ");


scanf("%s", pattern);

int match = patternMatch(text, pattern);

if (match != -1)
printf("Pattern found at position... %d\n", match + 1);
else
printf("Pattern not found.\n");

return 0;
}

OUTPUT
Case 1
Enter the main string… abbbababaab
Enter the pattern to search… abaa
Pattern found at position… 7

Case 2
Enter the main string… abbbababaab
Enter the pattern to search… bbaa
Pattern not found.

=====End of UNIT 1 =====

DR. V SREENIVASULU 35

You might also like