Ds chp2
Ds chp2
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:
• 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
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:
• 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.
Output:
10 14 19 26 27 31 33 35 42 44
=33
Output:
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:
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];
int main() {
int i, n, a[20];
cout << "Enter the number of elements: "; cin >> n;
selectionSort(a, n);
}
}
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>
}
}
}
int main() {
int i, n, a[20];
bubbleSort(a, n);
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
}
a[j + 1] = temp; // Insert nth element into the vacant position
}
}
int main() {
int i, n, a[10];
}
insertionSort(a, n);
cout << "Sorted list is as follows:"; for (i = 0;
i < n; i++) {
return 0;
Output:
Enter the number of elements: 4 Enter the
elements: 7 4 5 2
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)
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'
#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