cpp
examples
examples.cpp⚙️cpp
/**
* C++ Arrays - Examples
*
* This file demonstrates array concepts in C++ with practical examples.
* Each example is contained in its own function for easy understanding.
*
* Topics covered:
* - Array declaration and initialization
* - Accessing array elements
* - Array iteration methods
* - Multidimensional arrays
* - Arrays and functions
* - std::array (C++11)
* - Common array operations
*
* Compile: g++ -std=c++17 -Wall -Wextra examples.cpp -o examples
* Run: ./examples
*/
#include <iostream>
#include <iomanip>
#include <array>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <cstring>
using namespace std;
// ============================================================
// Example 1: Array Declaration and Initialization
// ============================================================
void example_declaration() {
cout << "\n=== Example 1: Array Declaration and Initialization ===" << endl;
// Method 1: Declaration only (garbage values)
int arr1[5]; // Not initialized!
cout << "Uninitialized (garbage values): ";
for (int i = 0; i < 5; i++) {
cout << arr1[i] << " "; // Undefined behavior!
}
cout << "(Don't rely on these values!)" << endl;
// Method 2: Full initialization
int arr2[5] = {10, 20, 30, 40, 50};
cout << "Fully initialized: ";
for (int x : arr2) cout << x << " ";
cout << endl;
// Method 3: Partial initialization
int arr3[5] = {1, 2}; // Remaining are 0
cout << "Partial init {1,2}: ";
for (int x : arr3) cout << x << " ";
cout << endl;
// Method 4: Zero initialization
int arr4[5] = {};
cout << "Zero initialized: ";
for (int x : arr4) cout << x << " ";
cout << endl;
// Method 5: Size inferred
int arr5[] = {1, 2, 3, 4, 5, 6, 7};
cout << "Size inferred: ";
for (int x : arr5) cout << x << " ";
cout << "(size = " << sizeof(arr5)/sizeof(arr5[0]) << ")" << endl;
// Method 6: Uniform initialization (C++11)
int arr6[3]{100, 200, 300};
cout << "Uniform init: ";
for (int x : arr6) cout << x << " ";
cout << endl;
}
// ============================================================
// Example 2: Accessing Array Elements
// ============================================================
void example_accessing() {
cout << "\n=== Example 2: Accessing Array Elements ===" << endl;
int arr[5] = {10, 20, 30, 40, 50};
// Reading elements
cout << "Array contents: ";
for (int x : arr) cout << x << " ";
cout << endl;
cout << "First element (arr[0]): " << arr[0] << endl;
cout << "Third element (arr[2]): " << arr[2] << endl;
cout << "Last element (arr[4]): " << arr[4] << endl;
// Modifying elements
arr[1] = 25;
arr[3] = arr[2] + arr[4];
cout << "After modifications: ";
for (int x : arr) cout << x << " ";
cout << endl;
// Pointer access
cout << "\n-- Pointer Access --" << endl;
int* ptr = arr;
cout << "*ptr (first): " << *ptr << endl;
cout << "*(ptr+2) (third): " << *(ptr + 2) << endl;
cout << "ptr[4] (last): " << ptr[4] << endl;
}
// ============================================================
// Example 3: Array Iteration Methods
// ============================================================
void example_iteration() {
cout << "\n=== Example 3: Array Iteration Methods ===" << endl;
int arr[] = {5, 10, 15, 20, 25};
int size = sizeof(arr) / sizeof(arr[0]);
// Method 1: Index-based for loop
cout << "Method 1 (index): ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
// Method 2: Range-based for loop (C++11)
cout << "Method 2 (range-for): ";
for (int x : arr) {
cout << x << " ";
}
cout << endl;
// Method 3: Pointer iteration
cout << "Method 3 (pointer): ";
for (int* ptr = arr; ptr < arr + size; ptr++) {
cout << *ptr << " ";
}
cout << endl;
// Method 4: std::begin/std::end
cout << "Method 4 (begin/end): ";
for (auto it = begin(arr); it != end(arr); ++it) {
cout << *it << " ";
}
cout << endl;
// Modifying with range-for (use reference)
cout << "\n-- Modifying elements --" << endl;
cout << "Original: ";
for (int x : arr) cout << x << " ";
cout << endl;
for (int& x : arr) {
x *= 2; // Double each element
}
cout << "Doubled: ";
for (int x : arr) cout << x << " ";
cout << endl;
}
// ============================================================
// Example 4: Array Size and Memory
// ============================================================
void example_size_memory() {
cout << "\n=== Example 4: Array Size and Memory ===" << endl;
int intArr[5] = {1, 2, 3, 4, 5};
double doubleArr[5] = {1.1, 2.2, 3.3, 4.4, 5.5};
char charArr[5] = {'a', 'b', 'c', 'd', 'e'};
cout << "int array[5]:" << endl;
cout << " Total size: " << sizeof(intArr) << " bytes" << endl;
cout << " Element size: " << sizeof(intArr[0]) << " bytes" << endl;
cout << " Element count: " << sizeof(intArr)/sizeof(intArr[0]) << endl;
cout << "\ndouble array[5]:" << endl;
cout << " Total size: " << sizeof(doubleArr) << " bytes" << endl;
cout << " Element size: " << sizeof(doubleArr[0]) << " bytes" << endl;
cout << " Element count: " << sizeof(doubleArr)/sizeof(doubleArr[0]) << endl;
cout << "\nchar array[5]:" << endl;
cout << " Total size: " << sizeof(charArr) << " bytes" << endl;
cout << " Element size: " << sizeof(charArr[0]) << " bytes" << endl;
cout << " Element count: " << sizeof(charArr)/sizeof(charArr[0]) << endl;
// C++17: std::size()
cout << "\nUsing std::size(): " << size(intArr) << " elements" << endl;
// Memory addresses
cout << "\n-- Memory Layout --" << endl;
cout << "Base address: " << intArr << endl;
for (int i = 0; i < 5; i++) {
cout << " intArr[" << i << "] at " << &intArr[i] << " = " << intArr[i] << endl;
}
}
// ============================================================
// Example 5: 2D Arrays (Matrices)
// ============================================================
void example_2d_arrays() {
cout << "\n=== Example 5: 2D Arrays (Matrices) ===" << endl;
// Declaration and initialization
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Print matrix
cout << "Matrix (3x4):" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
cout << setw(4) << matrix[i][j];
}
cout << endl;
}
// Access specific element
cout << "\nElement at [1][2]: " << matrix[1][2] << endl; // 7
// Sum of all elements
int sum = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
sum += matrix[i][j];
}
}
cout << "Sum of all elements: " << sum << endl;
// Row sums
cout << "\n-- Row Sums --" << endl;
for (int i = 0; i < 3; i++) {
int rowSum = 0;
for (int j = 0; j < 4; j++) {
rowSum += matrix[i][j];
}
cout << "Row " << i << " sum: " << rowSum << endl;
}
// Column sums
cout << "\n-- Column Sums --" << endl;
for (int j = 0; j < 4; j++) {
int colSum = 0;
for (int i = 0; i < 3; i++) {
colSum += matrix[i][j];
}
cout << "Col " << j << " sum: " << colSum << endl;
}
}
// ============================================================
// Example 6: Matrix Operations
// ============================================================
void example_matrix_operations() {
cout << "\n=== Example 6: Matrix Operations ===" << endl;
int A[2][3] = {{1, 2, 3}, {4, 5, 6}};
int B[2][3] = {{7, 8, 9}, {10, 11, 12}};
int C[2][3]; // Result
cout << "Matrix A:" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << setw(3) << A[i][j];
}
cout << endl;
}
cout << "\nMatrix B:" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << setw(3) << B[i][j];
}
cout << endl;
}
// Addition
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
cout << "\nA + B:" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << setw(3) << C[i][j];
}
cout << endl;
}
// Transpose
cout << "\n-- Transpose --" << endl;
int orig[2][3] = {{1, 2, 3}, {4, 5, 6}};
int trans[3][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
trans[j][i] = orig[i][j];
}
}
cout << "Original (2x3):" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << setw(3) << orig[i][j];
}
cout << endl;
}
cout << "Transposed (3x2):" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
cout << setw(3) << trans[i][j];
}
cout << endl;
}
}
// ============================================================
// Example 7: Arrays and Functions
// ============================================================
void printArray(const int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void modifyArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] *= 2;
}
}
int sumArray(const int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}
void example_functions() {
cout << "\n=== Example 7: Arrays and Functions ===" << endl;
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Original array: ";
printArray(arr, size);
cout << "Sum of elements: " << sumArray(arr, size) << endl;
modifyArray(arr, size);
cout << "After doubling: ";
printArray(arr, size);
// Demonstrating size decay
cout << "\n-- Size Decay Demonstration --" << endl;
cout << "sizeof(arr) in main: " << sizeof(arr) << " bytes" << endl;
// When passed to function, arr becomes pointer, losing size info
}
// ============================================================
// Example 8: C-Style Strings
// ============================================================
void example_cstrings() {
cout << "\n=== Example 8: C-Style Strings ===" << endl;
// Different ways to create
char str1[] = "Hello"; // Includes null terminator
char str2[6] = {'W', 'o', 'r', 'l', 'd', '\0'};
char str3[20] = "C++"; // Extra space filled with '\0'
cout << "str1: \"" << str1 << "\" (length: " << strlen(str1) << ")" << endl;
cout << "str2: \"" << str2 << "\" (length: " << strlen(str2) << ")" << endl;
cout << "str3: \"" << str3 << "\" (length: " << strlen(str3) << ")" << endl;
// sizeof vs strlen
cout << "\n-- sizeof vs strlen --" << endl;
cout << "sizeof(str1): " << sizeof(str1) << " (includes '\\0')" << endl;
cout << "strlen(str1): " << strlen(str1) << " (excludes '\\0')" << endl;
// String operations
cout << "\n-- String Operations --" << endl;
char dest[50];
strcpy(dest, str1);
cout << "After strcpy: \"" << dest << "\"" << endl;
strcat(dest, " ");
strcat(dest, str2);
cout << "After strcat: \"" << dest << "\"" << endl;
// Comparison
cout << "\n-- String Comparison --" << endl;
char a[] = "Apple";
char b[] = "Banana";
char c[] = "Apple";
cout << "strcmp(\"Apple\", \"Banana\"): " << strcmp(a, b) << " (negative = a < b)" << endl;
cout << "strcmp(\"Apple\", \"Apple\"): " << strcmp(a, c) << " (0 = equal)" << endl;
// Character iteration
cout << "\n-- Character Iteration --" << endl;
cout << "Characters in \"Hello\": ";
for (int i = 0; str1[i] != '\0'; i++) {
cout << str1[i] << " ";
}
cout << endl;
}
// ============================================================
// Example 9: std::array (C++11)
// ============================================================
void example_std_array() {
cout << "\n=== Example 9: std::array (C++11) ===" << endl;
// Declaration and initialization
array<int, 5> arr = {10, 20, 30, 40, 50};
cout << "Array contents: ";
for (int x : arr) cout << x << " ";
cout << endl;
// Size is part of the type
cout << "Size: " << arr.size() << endl;
cout << "Max size: " << arr.max_size() << endl;
cout << "Empty: " << boolalpha << arr.empty() << endl;
// Access methods
cout << "\n-- Access Methods --" << endl;
cout << "First (front()): " << arr.front() << endl;
cout << "Last (back()): " << arr.back() << endl;
cout << "arr[2]: " << arr[2] << endl;
cout << "arr.at(2): " << arr.at(2) << endl;
// Bounds checking with at()
try {
cout << "arr.at(10): ";
cout << arr.at(10) << endl;
} catch (const out_of_range& e) {
cout << "Exception: " << e.what() << endl;
}
// Fill
array<int, 5> zeros;
zeros.fill(0);
cout << "\nFilled with zeros: ";
for (int x : zeros) cout << x << " ";
cout << endl;
// Swap
array<int, 5> other = {1, 2, 3, 4, 5};
cout << "\nBefore swap:" << endl;
cout << " arr: "; for (int x : arr) cout << x << " "; cout << endl;
cout << " other: "; for (int x : other) cout << x << " "; cout << endl;
arr.swap(other);
cout << "After swap:" << endl;
cout << " arr: "; for (int x : arr) cout << x << " "; cout << endl;
cout << " other: "; for (int x : other) cout << x << " "; cout << endl;
// Comparison
array<int, 3> a = {1, 2, 3};
array<int, 3> b = {1, 2, 3};
array<int, 3> c = {1, 2, 4};
cout << "\n-- Comparison --" << endl;
cout << "{1,2,3} == {1,2,3}: " << (a == b) << endl;
cout << "{1,2,3} < {1,2,4}: " << (a < c) << endl;
}
// ============================================================
// Example 10: Common Array Algorithms
// ============================================================
void example_algorithms() {
cout << "\n=== Example 10: Common Array Algorithms ===" << endl;
int arr[] = {64, 25, 12, 22, 11, 90};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Original: ";
for (int x : arr) cout << x << " ";
cout << endl;
// Find min and max
int minVal = *min_element(arr, arr + size);
int maxVal = *max_element(arr, arr + size);
cout << "Min: " << minVal << ", Max: " << maxVal << endl;
// Sum
int sum = accumulate(arr, arr + size, 0);
cout << "Sum: " << sum << endl;
// Average
double avg = static_cast<double>(sum) / size;
cout << "Average: " << fixed << setprecision(2) << avg << endl;
// Sort
sort(arr, arr + size);
cout << "Sorted (asc): ";
for (int x : arr) cout << x << " ";
cout << endl;
sort(arr, arr + size, greater<int>());
cout << "Sorted (desc): ";
for (int x : arr) cout << x << " ";
cout << endl;
// Reverse
reverse(arr, arr + size);
cout << "Reversed: ";
for (int x : arr) cout << x << " ";
cout << endl;
// Find
int target = 25;
int* found = find(arr, arr + size, target);
if (found != arr + size) {
cout << "Found " << target << " at index " << (found - arr) << endl;
}
// Count
int arr2[] = {1, 2, 3, 2, 4, 2, 5};
int countOf2 = count(arr2, arr2 + 7, 2);
cout << "Count of 2s in {1,2,3,2,4,2,5}: " << countOf2 << endl;
// Binary search (requires sorted array)
sort(arr, arr + size);
cout << "\nBinary search in sorted array: ";
for (int x : arr) cout << x << " ";
cout << endl;
target = 22;
bool exists = binary_search(arr, arr + size, target);
cout << "Does " << target << " exist? " << boolalpha << exists << endl;
}
// ============================================================
// Example 11: Multi-dimensional std::array
// ============================================================
void example_multidim_std_array() {
cout << "\n=== Example 11: Multi-dimensional std::array ===" << endl;
// 2D array using nested std::array
array<array<int, 4>, 3> matrix = {{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
}};
cout << "Matrix (3x4):" << endl;
for (const auto& row : matrix) {
for (int val : row) {
cout << setw(4) << val;
}
cout << endl;
}
cout << "\nElement at [1][2]: " << matrix[1][2] << endl;
cout << "Number of rows: " << matrix.size() << endl;
cout << "Number of columns: " << matrix[0].size() << endl;
// Calculate sum
int sum = 0;
for (const auto& row : matrix) {
for (int val : row) {
sum += val;
}
}
cout << "Sum: " << sum << endl;
}
// ============================================================
// Example 12: Array Patterns and Use Cases
// ============================================================
void example_patterns() {
cout << "\n=== Example 12: Array Patterns and Use Cases ===" << endl;
// Frequency counter
cout << "-- Frequency Counter --" << endl;
int data[] = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};
int freq[5] = {}; // Assuming values 1-4
for (int x : data) {
freq[x]++;
}
for (int i = 1; i <= 4; i++) {
cout << i << " appears " << freq[i] << " times" << endl;
}
// Two pointers technique
cout << "\n-- Two Pointers (Palindrome Check) --" << endl;
char str[] = "radar";
int left = 0, right = strlen(str) - 1;
bool isPalindrome = true;
while (left < right) {
if (str[left] != str[right]) {
isPalindrome = false;
break;
}
left++;
right--;
}
cout << "\"" << str << "\" is " << (isPalindrome ? "" : "not ") << "a palindrome" << endl;
// Sliding window (max sum of k consecutive elements)
cout << "\n-- Sliding Window (max sum of 3 elements) --" << endl;
int nums[] = {1, 4, 2, 10, 2, 3, 1, 0, 20};
int n = sizeof(nums) / sizeof(nums[0]);
int k = 3;
int windowSum = 0;
for (int i = 0; i < k; i++) {
windowSum += nums[i];
}
int maxSum = windowSum;
for (int i = k; i < n; i++) {
windowSum = windowSum - nums[i - k] + nums[i];
maxSum = max(maxSum, windowSum);
}
cout << "Array: "; for (int x : nums) cout << x << " "; cout << endl;
cout << "Max sum of " << k << " consecutive: " << maxSum << endl;
}
// ============================================================
// Main Function - Run All Examples
// ============================================================
int main() {
cout << "╔════════════════════════════════════════════════════════════╗" << endl;
cout << "║ C++ ARRAYS - COMPREHENSIVE EXAMPLES ║" << endl;
cout << "╚════════════════════════════════════════════════════════════╝" << endl;
example_declaration();
example_accessing();
example_iteration();
example_size_memory();
example_2d_arrays();
example_matrix_operations();
example_functions();
example_cstrings();
example_std_array();
example_algorithms();
example_multidim_std_array();
example_patterns();
cout << "\n╔════════════════════════════════════════════════════════════╗" << endl;
cout << "║ ALL EXAMPLES COMPLETE ║" << endl;
cout << "╚════════════════════════════════════════════════════════════╝" << endl;
return 0;
}