
This blog post covers various techniques for solving array-related problems in programming, including searching for elements, reversing arrays, finding maximum values, and using functions to manipulate arrays. It provides step-by-step explanations and code examples to enhance understanding.
Hello, coder army! In this lecture, we will dive into some array-related questions to enhance our hands-on practice. We will also explore how to pass arrays to functions. Without further ado, let's get started!
Given an array, we need to search for a specific element and return its index if present. If the element is not found, we will return -1.
Consider the array: arr = [10, 20, 11, 8, 4]. If we want to find the element 11, we will check each element sequentially:
11 equal to 10? No.11 equal to 20? No.11 equal to 11? Yes! Return index 2.If we search for 18, we will check all elements and find that it is not present, thus returning -1.
To implement this, we can use a loop to iterate through the array:
int searchElement(int arr[], int n, int x) {
for (int i = 0; i < n; i++) {
if (arr[i] == x) {
return i; // Element found
}
}
return -1; // Element not found
}
The task is to reverse the elements of a given array.
For the array arr = [9, 8, 4, 7, 11, 6], the reversed array should be [6, 11, 7, 4, 8, 9].
We can create a new array to store the reversed elements:
void reverseArray(int arr[], int n) {
int temp[n];
for (int i = 0; i < n; i++) {
temp[i] = arr[n - 1 - i];
}
for (int i = 0; i < n; i++) {
arr[i] = temp[i];
}
}
Alternatively, we can reverse the array in place without using extra space:
void reverseArrayInPlace(int arr[], int n) {
int start = 0, end = n - 1;
while (start < end) {
swap(arr[start], arr[end]);
start++;
end--;
}
}
Given an array, find the second largest distinct element.
For the array arr = [12, 35, 1, 10, 34], the second largest element is 34.
To find the second largest element, we can first find the maximum and then search for the next largest:
int findSecondMax(int arr[], int n) {
int max = INT_MIN, secondMax = INT_MIN;
for (int i = 0; i < n; i++) {
if (arr[i] > max) {
secondMax = max;
max = arr[i];
} else if (arr[i] > secondMax && arr[i] != max) {
secondMax = arr[i];
}
}
return secondMax;
}
To pass an array to a function, we can simply use the array name and its size as parameters:
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printArray(arr, 5);
return 0;
}
In this lecture, we covered various techniques for solving array-related problems, including searching for elements, reversing arrays, and finding maximum values. We also learned how to pass arrays to functions effectively. I hope you found this lecture helpful and engaging. If you enjoyed it, please like and share! See you in the next lecture!
Paste a YouTube link and let Magica create the key takeaways.
Summarize another video