Welcome to our comprehensive guide on C++ Array Functions! In this lesson, we'll learn about arrays, their types, and various functions to manipulate them. Let's dive in!
An array is a collection of variables of the same data type stored in contiguous memory locations. In C++, arrays can be of various types like integer arrays, character arrays, and floating-point arrays.
int arr[5] = {1, 2, 3, 4, 5}; // Integer Array
char arrCh[3] = {'H', 'e', 'l'}; // Character Array
float arrF[2] = {1.2, 3.4}; // Floating-Point Arrayš” Pro Tip: The size of the array is determined at compile time.
C++ provides several built-in functions to manipulate arrays. Here are some of the most commonly used ones:
sizeof() šThe sizeof() function returns the size of the array in bytes.
int arr[5] = {1, 2, 3, 4, 5};
std::cout << "Size of the array: " << sizeof(arr) << "\n";arr[index] šAccessing an array using an index retrieves the value at that index.
int arr[5] = {1, 2, 3, 4, 5};
std::cout << "First element: " << arr[0] << "\n";arr_name[start..end] šAccessing an array using a range retrieves values within that range.
int arr[5] = {1, 2, 3, 4, 5};
std::cout << "Elements from 2 to 4: ";
for(int i = 1; i < 4; i++) {
std::cout << arr[i] << " ";
}
std::cout << "\n";array_name.length() šThe length() function is not a built-in function in C++, but you can write a simple function to get the array length:
int arr[5] = {1, 2, 3, 4, 5};
int length = sizeof(arr) / sizeof(arr[0]);
std::cout << "Array length: " << length << "\n";Let's create a program that takes user input for an array, finds the maximum and minimum values, and displays the sum of even numbers.
#include<iostream>
using namespace std;
void findMaxMinAndSumEven(int arr[], int size) {
int max = arr[0];
int min = arr[0];
int sumEven = 0;
for(int i = 0; i < size; i++) {
if(arr[i] % 2 == 0) {
sumEven += arr[i];
}
if(arr[i] > max) {
max = arr[i];
}
if(arr[i] < min) {
min = arr[i];
}
}
cout << "Maximum: " << max << "\n";
cout << "Minimum: " << min << "\n";
cout << "Sum of even numbers: " << sumEven << "\n";
}
int main() {
int size;
cout << "Enter the array size: ";
cin >> size;
int arr[size];
cout << "Enter the array elements:\n";
for(int i = 0; i < size; i++) {
cin >> arr[i];
}
findMaxMinAndSumEven(arr, size);
return 0;
}What is an array in C++?
How do you find the size of an array using C++?
What is the purpose of the `findMaxMinAndSumEven` function in the practical example?