0% found this document useful (0 votes)
11 views18 pages

Ds chp2

Chapter 2 introduces arrays and strings, explaining that an array is a collection of elements of the same data type, with linear and multi-dimensional arrays as its types. It covers memory representation, searching algorithms like linear and binary search, and sorting techniques including selection, bubble, and insertion sort. Additionally, it defines strings as arrays of characters terminated by a null character.

Uploaded by

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

Ds chp2

Chapter 2 introduces arrays and strings, explaining that an array is a collection of elements of the same data type, with linear and multi-dimensional arrays as its types. It covers memory representation, searching algorithms like linear and binary search, and sorting techniques including selection, bubble, and insertion sort. Additionally, it defines strings as arrays of characters terminated by a null character.

Uploaded by

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

CHAPTER 2: INTRODUCTION TO ARRAYS AND STRINGS

2.1 ARRAY
• An array is a collection of elements of the same data-type.
• You can access any element by using:
→ name of the array
→ position of the element in the array, i.e., the index
• Two types of arrays include:
1) Linear-array
2) Multi-dimensional-array
2.1.1 LINEAR-ARRAYS
• A linear-array stores a collection of elements of the same data-type in a sequential manner.
• It is also known as a one-dimensional array (1D array).
• In memory, all the elements of a linear-array are stored in continuous memory locations, one after the other.
2.1.1.1 MEMORY REPRESENTATION OF LINEAR-ARRAYS
• The syntax for declaring a linear-array is as follows:
data_type array_name[array_size];
where:
data_type can be int, float, or char.
array_name is the name of the array.
array_size specifies the total number of elements in the array.
• Example:
int age[5];
• This creates a linear-array with 5 elements, where each element can store an integer value.
• The above code can be pictorially represented as:

age[0] age[1] age[2] age[3] age[4]

• The first element is indexed as age[0], and the last element is indexed as age[4].
MEMORY CALCULATION
• The memory-address of an element in a linear-array is calculated using the formula:
Address of array[i] = Base-address of array + i * size_of_element
Where:
i is the index of the element.
size_of_element is the size of each element (e.g., 4 bytes for an int).
• Example:
If base-address of the array age is 0x2000, and the size of each element is 4 bytes:
Address of age[0] = 0x2000.
Address of age[1] = 0x2004 (0+1)×4=40+1)×4=4 bytes after age[0]).
Address of age[2] = 0x2008 (0+2)×4=80+2)×4=8 bytes after age[0]).
Address of age[3] = 0x200C (0+3)×4=120+3)×4=12 bytes after age[0]).
Address of age[4] = 0x2010 (0+4)×4=160+4)×4=16 bytes after age[0]).
PICTORIAL REPRESENTATION

Index Element Address


age[0] First element 0x2000
age[1] Second element 0x2004
age[2] Third element 0x2008
age[3] Fourth element 0x200c
age[4] Fifth element 0x2010

2.1.2 MULTIDIMENSIONAL-ARRAYS
• A multidimensional-array stores a collection of elements in a tabular format consisting of rows and columns (or higher
dimensions).
• In memory, all the elements are stored in continuous memory-locations row by row or column by column.
2.1.2.1 MEMORY REPRESENTATION OF MULTIDIMENSIONAL-ARRAYS
• The syntax for declaring a two-dimensional array is as follows:
data_type array_name[row_size][column_size];
Where:
data_type can be int, float, or char.
array_name is the name of the array.
row_size specifies the number of rows.
column_size specifies the number of columns.
• Example:
int matrix[2][3];
• This creates a 2D array with 2 rows and 3 columns, where a total of 2×3=6 elements can be stored.
• The above code can be pictorially represented as:

matrix[0][0] matrix[0][1] matrix[0][2]


matrix[1][0] matrix[1][1] matrix[1][2]

• The first element of the array is matrix[0][0], and the last element is matrix[1][2]
MEMORY CALCULATION
• The memory-address of an element in a multidimensional-array is calculated as:
Address of matrix[i][j] = Base-address of matrix + (i * number_of_columns + j) * size_of_element
Where:
i is the row index.
j is the column index.
number_of_columns is the total columns in the array.
size_of_element is the size of each element (e.g., 4 bytes for an int).
• Example:
If the base-address of the array is 0x4000, and the size of each element is 4 bytes:
Address of matrix[0][0] = 0x4000.

Address of matrix[0][1] = 0x4004 (0∗3+1)×4=40∗3+1)×4=4 bytes after


matrix[0][0]).
...
...

Address of matrix[1][2] = 0x4014 (1∗3+2)×4=201∗3+2)×4=20 bytes after


matrix[0][0]).

Index Element Address

matix[0] First element 0x4000


[0]

matix[0] Second element 0x4004


[1]

matix[0] Third element 0x4008


[2]

matix[1] Fourth element 0x400c


[0]

matix[1] Fifth element 0x4010


[1]

matix[1] Sixth element 0x4014


[2]

2.1.3 SINGLE-DIMENSIONAL ARRAY VS TWO-DIMENSIONAL ARRAY


2.2 SEARCHING
• Definition: Identifying the location of a specific element in the data-structure.
• Purpose: Helps locate and access data quickly.
• Example: Linear search, Binary search.
2.2.1 SEQUENTIAL SEARCH (LINEAR SEARCH)
• This technique finds the position of a key-element within an unsorted-array.
Algorithm
1) Compare with Key-element: Compare the first element of the list with the
key-element.
2) Match Found: If the element matches the key-element, return the index of the
element.
3) Continue Search: If the element does not match the key-element, move to
the next element in the list and repeat steps 1-2 until the key-element is found
or the end of the list is reached.
Program to implement linear Search using iterative function
#include <iostream>
int linearSearch(int a[], int key, int n) {
for (int i = 0; i < n; i++) {
if (key == a[i]) {
return 1; // Element found
}
}
return -1; // Element not found
}
int main() {
int a[10];
int n, key, found = -1;
cout << "Enter number of elements: ";
cin >> n;
cout << "Enter the elements: ";
for (int i = 0; i < n; i++) {
cin >> a[i];
}
cout << "Enter the element to be searched: ";
cin >> key;
found = linearSearch(a, key, n);
if (found == -1) {
cout << "Element is not present in the array" << endl;
} else {
cout << "Element is present in the array" << endl;
}
return 0;
}

Output:

Enter number of elements: 10

Enter the elements: 10 14 19 26 27 31 33 42 44

Enter the element to be searched: 27

10 14 19 26 27 31 33 35 42 44
=33

2.2.2 BINARY SEARCH


• This technique finds the position of a key-element within a sorted-array.
Algorithm
1) Initialize Search Range: Given a sorted-array and a key-element to search
for, initialize two variables:
low = 0
high = length of the array - 1.
2) Repeat Until Search Range is Valid: While low is less than or equal to high:
i) Calculate the mid-index of the array as (low + high) // 2.
ii) Key Found: If the element at the mid-index of the array is equal to the keyelement, return mid.
iii) Key Greater: If the element at the mid-index is less than the key-element,
set low = mid + 1.
iv) Key Smaller: If the element at the mid-index is greater than the key
element, set high = mid - 1.
3) Key Not Found: If the key-element is not found in the array, return -1.
Program to implement Binary Search using Iterative function
#include <iostream>
int binarySearch(int a[], int key, int low, int high) {
int mid;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] == key) {
return mid; // Element found at index mid
} else if (a[mid] < key) {
low = mid + 1; // Search in the right half
} else {
high = mid - 1; // Search in the left half
}
}
return -1; // Element not found
}
int main() {
int a[10];
int n, key, found = -1;
cout << "Enter number of elements: ";
cin >> n;
cout << "Enter the elements in sorted order: ";
for (int i = 0; i < n; i++) {
cin >> a[i];
}
cout << "Enter the element to be searched: ";
cin >> key;
found = binarySearch(a, key, 0, n - 1);
if (found == -1) {
cout << "Element is not present in the array" << endl;
} else {
cout << "Element is present at index " << found << endl;
}
return 0;
}

Output:

Enter number of elements:7

Enter the elements: 11 17 18 45 50 71


95

Enter the element to be searched: 50

2.1 SORTING
• Definition: Arranges the elements of an array in a specific order (ascending or descending).
• Purpose: Improves search performance and organizes data logically
• Example: Selection sort, Bubble sort, Insertion sort. Definition:

2.1.1 SELECTION SORT (SEQUENTIAL SORT)


• Selection sort is a simple sorting technique.
• It is called "selection" sort because it selects the minimum element and moves it to the beginning of the
list.
Algorithm
1) Find the Smallest Element: Find the smallest element in the list and swap it with the first element.
2) Find the Next Smallest Element: Find the second smallest element in the list and swap it with the
second element.
3) Repeat the Process: Repeat this process until the entire list is sorted.
#include <iostream>
void selectionSort(int a[], int n) { int i, j, min,
temp;

for (i = 0; i < n - 1; i++) {


min = i; // Assign min to point to the first element in the unsorted list

for (j = i + 1; j < n; j++) {

if (a[min] > a[j]) { // If the minimum element > nth element min = j; // Re-
assign min to point to the nth element
}

}
// Swap the minimum element with the first element in the unsorted list temp = a[i];

a[i] = a[min]; a[min] =


temp;
}

int main() {
int i, n, a[20];
cout << "Enter the number of elements: "; cin >> n;

cout << "Enter the elements: "; for (i = 0;


i < n; i++) {

cin >> a[i];


}

selectionSort(a, n);

cout << "Sorted list is as follows:" << endl; for (i = 0; i <


n; i++) {
cout << a[i] << endl;

}
}

Output:
Enter the number of elements: 4 Enter the
elements: 7 5 4 2
2.1.2 BUBBLE SORT
• Bubble sort is a simple sorting technique.
• It is called "bubble sort" because larger elements "bubble" to the bottom of the list
Algorithm
1) Start with the First Element: Start at the first element (index 0) of the array.
2) Compare and Swap Elements: Compare the first and second elements. If the first element
is greater than the second element, swap them.
3) Move to the Next Pair: Move to the next pair of elements (index 1 and index 2), and repeat the
comparison and swapping process. Keep moving through the list until you reach the end of the list.
4) Largest Element at the End: At this point, the largest element will be at the end of the list.
5) Repeat for Unsorted Part: Repeat the entire process through the unsorted part of the list in the
next iteration.
6) Continue Until Sorted: Keep repeating steps 2-5 until the list is fully sorted.
Program to sort N numbers by bubble sort
#include <iostream>

void bubbleSort(int a[], int n) { int i, j,


temp;

for (i = 0; i < n; i++) {

for (j = 0; j < n - i - 1; j++) {


if (a[j] > a[j + 1]) { // If nth element > (n+1)th element, then swap them temp = a[j];

a[j] = a[j + 1]; a[j + 1] =


temp;
}

}
}
}

int main() {
int i, n, a[20];

cout << "Enter the number of elements: "; cin >> n;

cout << "Enter the elements: "; for (i = 0;


i < n; i++) {

cin >> a[i];


}

bubbleSort(a, n);

cout << "Sorted list is as follows:" << endl; for (i = 0; i <


n; i++) {
cout << a[i] << endl;

return 0;
}

Output:
Enter the number of elements: 4 Enter the
elements: 5 3 4 2
2.1.3 INSERTION SORT
• Insertion sort is a simple sorting technique
Algorithm
1) Start with the Second Element: Start with the second element of the list.
2) Compare and Swap: Compare the second element with the first element. If the second
element is smaller, swap them.
3) Move to the Next Element: Move to the third element and compare it with the second and first
elements. Swap it with the first or second element if it is smaller.
4) Repeat for Remaining Elements: Repeat this process for the remaining elements until the entire
list is sorted.
Program to sort N numbers by Insertion sort
#include <iostream>
void insertionSort(int a[], int n) { int i, j,
temp;
for (i = 1; i < n; i++) {
temp = a[i]; // temp is the index to the nth element j = i - 1; // j
is the index to the (n-1)th element

// Check if nth element < (n-1)th element while


((temp < a[j]) && (j >= 0)) {
a[j + 1] = a[j]; // If yes, insert (n-1)th element into nth position j = j - 1;

}
a[j + 1] = temp; // Insert nth element into the vacant position
}
}

int main() {
int i, n, a[10];

cout << "Enter the number of elements: "; cin >> n;


cout << "Enter the elements: "; for (i =
0; i < n; i++) {
cin >> a[i];

}
insertionSort(a, n);
cout << "Sorted list is as follows:"; for (i = 0;
i < n; i++) {

cout << "\n" << a[i];


}

return 0;
Output:
Enter the number of elements: 4 Enter the
elements: 7 4 5 2

Sorted list is as follows: 2 4 5 7


2.2 STRING DEFINITION
Definition
• A string consists of an array of characters (`char`).
• It stores a sequence of characters in contiguous memory-locations.
• A null character (`'\0'`) terminates strings, marking the end of the sequence.
Declaration and Initialization
• Strings can be declared and initialized using C-style character arrays or using
`string`.
• Example:
char s[10] = "rama"; // C-style string
string s = "rama"; // string
• The above code can be pictorially represented as shown below:

• Program to illustrate read and write operations on strings:


#include <iostream> using
namespace std;

int main() {
// Reading a string from user input char
str[10];
cout << "Enter a string: ";
cin.getline(str, 10); // Reads up to 9 characters (leaves space for null terminator)

// Writing the string to standard output cout << "You


entered: " << str << endl;

return 0;
}

Output:
Enter a string: rama You
entered: rama
2.2.1 BASIC OPERATIONS ON STRINGS
1) Length of a String
• Use the length() or size() method to find the number of characters in a string.
• Syntax:
`str.size()` or `str.length()`
• Example:
string text = "gcwmaddur”
int len = text.size(); // len will be 9

2) Concatenation
• Combine two strings into one using the append() method.
• Syntax:
`str.append(suffix);`
• Example:
string name = "krishna";
greeting.append("kumar"); // name now contains "krishnakumar"

3) Substring Extraction
• Extract a portion of the string using the substr() method.
• Syntax:
`str.substr(start_pos, length);` Where
start_pos: The starting position in the string (0-based index). length: The number of
characters to extract (optional). If omitted, the substring extends to the end of the
string.
• Example:
string message = "Hello, World!";
string sub = message.substr(7, 5); // Extracts "World"

4) Comparison
• Compare two strings using the compare() method or relational operators.
• Syntax:
str1.compare(str2); Returns:
0 if str1 is equal to str2.
A positive value if str1 is greater than str2. A negative
value if str1 is less than str2.
Example:
string str1 = "Hello";
string str2 = "World";
if (str1.compare(str2) == 0)
cout << "Strings are equal" << endl;
else
cout << "Strings are not equal" << endl;
1) Find
• Search for a substring using the find() method.
• Syntax:
`str.find(substring);` Returns:
If the substring is found, it returns the index (position) of the first occurrence of the
substring in the string.
If the substring is not found, it returns string::npos (a constant indicating the
absence of the substring).
• Example:
string sentence = "The quick brown fox jumps over the lazy dog.";
size_t found = sentence.find("fox");
// found will be 16

2) Replace
• Replace a portion of the string using the replace() method.
• Syntax:
`str.replace(start_pos, length_to_replace, new_str);` Where
start_pos: The starting position where the replacement begins length_to_replace: The number of
characters to be replaced.
new_str: The string that will replace the characters in the original string.
• Example:
string message = "Hello, World!";
message.replace(7, 5, "Universe"); // Replaces "World" with "Universe"
// message now contains "Hello, Universe!"

3) tolower()
• Convert uppercase letters to lowercase using the tolower() function.
• Syntax:
char tolower(char ch);
Where
ch: The character to be converted to lowercase.
Returns the lowercase equivalent if the character is uppercase; otherwise, returns the character
unchanged.
• Example:
char ch = 'A';
cout << tolower(ch); // Output: 'a'

4) toupper()
• Convert lowercase letters to uppercase using the toupper() function.
• Syntax:
char toupper(char ch);
Where
ch: The character to be converted to uppercase.
Returns the uppercase equivalent if the character is lowercase; otherwise, returns the character
unchanged.
• Example:
char ch = 'b';
cout << toupper(ch); // Output: 'B'

Program to convert a string of uppercase letters to lowercase and vice versa

#include <iostream>

int main()
{ string str;
cout << "Enter a string: "; cin >>
str;
for (int i = 0; i < str.length(); i++) { if
(isupper(str[i]))
str[i] = tolower(str[i]); else if
(islower(str[i]))
str[i] = toupper(str[i]);
}
cout << "Converted string: " << str << endl; return 0;
}

Output:
Enter a string: HeLLo
Converted string: hEllO

2.3 APPLICATIONS OF ARRAYS


1) Data Storage
• Arrays store a fixed number of elements of the same data-type.
• Example: Storing the marks of students in a class.
2) Matrix Representation
• Two-dimensional arrays represent matrices in mathematical operations.
• Applications include:
o Solving linear algebra problems.
o Representing graphs in adjacency matrices.
o Image processing.
3) Searching and Sorting
• Arrays efficiently implement search and sort algorithms.
• Example:
o Searching: Linear search, Binary search.
o Sorting: Bubble sort, Insertion sort, Selection sort etc.
4) Static Data Allocation
• Arrays allocate memory at compile time for tasks where the number of elements remains fixed.
• Example: Representing fixed-size buffers in embedded systems.
5) Representation of Other Data-structures
• Arrays help implement more complex data-structures such as
o Stacks
o Queues
o Heaps
6) Simulation and Gaming
• Arrays simulate various real-world systems in games.
• Example:
o Representing player scores and game levels.
o Grids in board games like chess or tic-tac-toe.
7) String Manipulation
• Arrays of characters (char[]) create and manipulate strings in C-style programming.
• Useful in low-level string operations.
8) Database Management
• Arrays store and manage records in databases where fixed-size fields are required.
• Example: Employee records, student IDs, etc.
9) Signal Processing
• Arrays store and process signals in applications such as
o Audio and video processing.
o Digital Signal Processing (DSP).
10) Numerical Computations
• Arrays play a critical role in performing numerical computations.
• Example: Statistical analysis and Solving equations.
11) Real-Time Applications
• Arrays support real-time applications where memory efficiency is critical.
• Example
o Sensor data storage in IoT.
o Storing time-series data.

You might also like