C++ Array Functions šŸŽÆ

beginner
10 min

C++ Array Functions šŸŽÆ

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!

Understanding Arrays šŸ“

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.

cpp
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.

Array Functions šŸ“

C++ provides several built-in functions to manipulate arrays. Here are some of the most commonly used ones:

1. sizeof() šŸ“

The sizeof() function returns the size of the array in bytes.

cpp
int arr[5] = {1, 2, 3, 4, 5}; std::cout << "Size of the array: " << sizeof(arr) << "\n";

2. arr[index] šŸ“

Accessing an array using an index retrieves the value at that index.

cpp
int arr[5] = {1, 2, 3, 4, 5}; std::cout << "First element: " << arr[0] << "\n";

3. arr_name[start..end] šŸ“

Accessing an array using a range retrieves values within that range.

cpp
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";

4. 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:

cpp
int arr[5] = {1, 2, 3, 4, 5}; int length = sizeof(arr) / sizeof(arr[0]); std::cout << "Array length: " << length << "\n";

Practical Example šŸ’”

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.

cpp
#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; }

Quiz šŸ’”

Quick Quiz
Question 1 of 1

What is an array in C++?

Quick Quiz
Question 1 of 1

How do you find the size of an array using C++?

Quick Quiz
Question 1 of 1

What is the purpose of the `findMaxMinAndSumEven` function in the practical example?