cpp
Working With Data
02_Working_With_Data⚙️cpp
/**
* ============================================================
* C++ ARRAYS
* ============================================================
*
* This file covers:
* - Array declaration and initialization
* - Accessing array elements
* - Array operations
* - Multidimensional arrays
* - Arrays and functions
* - C-style strings (character arrays)
*
* Compile: g++ -std=c++17 -Wall 01_arrays.cpp -o arrays
* Run: ./arrays
*
* ============================================================
*/
#include <iostream>
#include <iomanip>
#include <cstring> // For C-style string functions
#include <algorithm> // For sort, etc.
using namespace std;
// Function prototypes
void printArray(int arr[], int size);
void modifyArray(int arr[], int size);
int sumArray(const int arr[], int size);
int main() {
cout << "============================================" << endl;
cout << " C++ ARRAYS" << endl;
cout << "============================================" << endl << endl;
// ========================================================
// PART 1: ARRAY DECLARATION AND INITIALIZATION
// ========================================================
cout << "--- PART 1: DECLARATION & INITIALIZATION ---" << endl << endl;
// Declaration with size
int numbers[5]; // Uninitialized - contains garbage
// Declaration with initialization
int ages[5] = {25, 30, 35, 40, 45};
// Partial initialization (rest are 0)
int partial[5] = {1, 2}; // {1, 2, 0, 0, 0}
// Initialize all to zero
int zeros[5] = {0}; // All zeros
int zeros2[5] = {}; // All zeros (C++11)
// Let compiler determine size
int autoSize[] = {10, 20, 30, 40, 50, 60};
int arraySize = sizeof(autoSize) / sizeof(autoSize[0]);
// Display arrays
cout << "ages array: ";
for (int i = 0; i < 5; i++) {
cout << ages[i] << " ";
}
cout << endl;
cout << "partial array: ";
for (int i = 0; i < 5; i++) {
cout << partial[i] << " ";
}
cout << endl;
cout << "autoSize array (size " << arraySize << "): ";
for (int i = 0; i < arraySize; i++) {
cout << autoSize[i] << " ";
}
cout << endl;
// Array size must be constant
const int SIZE = 10;
int fixedArray[SIZE];
// C++11: constexpr for array sizes
constexpr int BUFFER_SIZE = 256;
char buffer[BUFFER_SIZE];
cout << endl;
// ========================================================
// PART 2: ACCESSING ARRAY ELEMENTS
// ========================================================
cout << "--- PART 2: ACCESSING ELEMENTS ---" << endl << endl;
int scores[5] = {85, 90, 78, 92, 88};
// Access by index (0-based)
cout << "scores[0] = " << scores[0] << endl;
cout << "scores[2] = " << scores[2] << endl;
cout << "scores[4] = " << scores[4] << endl;
// Modify elements
scores[1] = 95; // Change second element
cout << "After modification, scores[1] = " << scores[1] << endl;
// First and last elements
int size = sizeof(scores) / sizeof(scores[0]);
cout << "First element: " << scores[0] << endl;
cout << "Last element: " << scores[size - 1] << endl;
// ⚠️ WARNING: No bounds checking!
// scores[10] = 100; // UNDEFINED BEHAVIOR - may crash or corrupt memory
cout << endl;
// ========================================================
// PART 3: ARRAY OPERATIONS
// ========================================================
cout << "--- PART 3: ARRAY OPERATIONS ---" << endl << endl;
int data[] = {64, 34, 25, 12, 22, 11, 90};
int dataSize = sizeof(data) / sizeof(data[0]);
// Sum of elements
int sum = 0;
for (int i = 0; i < dataSize; i++) {
sum += data[i];
}
cout << "Sum: " << sum << endl;
// Average
double average = static_cast<double>(sum) / dataSize;
cout << "Average: " << fixed << setprecision(2) << average << endl;
// Find minimum and maximum
int minVal = data[0], maxVal = data[0];
for (int i = 1; i < dataSize; i++) {
if (data[i] < minVal) minVal = data[i];
if (data[i] > maxVal) maxVal = data[i];
}
cout << "Minimum: " << minVal << endl;
cout << "Maximum: " << maxVal << endl;
// Linear search
int searchValue = 25;
int foundIndex = -1;
for (int i = 0; i < dataSize; i++) {
if (data[i] == searchValue) {
foundIndex = i;
break;
}
}
cout << "Index of " << searchValue << ": " << foundIndex << endl;
// Copy array
int dataCopy[7];
for (int i = 0; i < dataSize; i++) {
dataCopy[i] = data[i];
}
// Using std::copy (modern way)
int dataCopy2[7];
copy(begin(data), end(data), begin(dataCopy2));
// Reverse array
cout << "Original: ";
printArray(data, dataSize);
for (int i = 0; i < dataSize / 2; i++) {
int temp = data[i];
data[i] = data[dataSize - 1 - i];
data[dataSize - 1 - i] = temp;
}
cout << "Reversed: ";
printArray(data, dataSize);
// Restore original
reverse(data, data + dataSize);
// Sort array
sort(data, data + dataSize);
cout << "Sorted: ";
printArray(data, dataSize);
cout << endl;
// ========================================================
// PART 4: RANGE-BASED FOR LOOP WITH ARRAYS
// ========================================================
cout << "--- PART 4: RANGE-BASED FOR ---" << endl << endl;
int values[] = {1, 2, 3, 4, 5};
// Read-only iteration
cout << "Read-only: ";
for (int val : values) {
cout << val << " ";
}
cout << endl;
// Modify elements (use reference)
cout << "After doubling: ";
for (int& val : values) {
val *= 2;
}
for (int val : values) {
cout << val << " ";
}
cout << endl;
// With auto
cout << "With auto: ";
for (auto val : values) {
cout << val << " ";
}
cout << endl;
cout << endl;
// ========================================================
// PART 5: MULTIDIMENSIONAL ARRAYS
// ========================================================
cout << "--- PART 5: MULTIDIMENSIONAL ARRAYS ---" << endl << endl;
// 2D array declaration
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Accessing elements
cout << "matrix[1][2] = " << matrix[1][2] << " (row 1, col 2)" << endl;
// Display 2D array
cout << "\n2D Array (3x4 matrix):" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
cout << setw(4) << matrix[i][j];
}
cout << endl;
}
// Row sum and column sum
cout << "\nRow sums: ";
for (int i = 0; i < 3; i++) {
int rowSum = 0;
for (int j = 0; j < 4; j++) {
rowSum += matrix[i][j];
}
cout << rowSum << " ";
}
cout << endl;
// 3D array
int cube[2][3][4] = {
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
},
{
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24}
}
};
cout << "\n3D Array [2][3][4]:" << endl;
for (int i = 0; i < 2; i++) {
cout << "Layer " << i << ":" << endl;
for (int j = 0; j < 3; j++) {
cout << " ";
for (int k = 0; k < 4; k++) {
cout << setw(3) << cube[i][j][k];
}
cout << endl;
}
}
cout << endl;
// ========================================================
// PART 6: ARRAYS AND FUNCTIONS
// ========================================================
cout << "--- PART 6: ARRAYS AND FUNCTIONS ---" << endl << endl;
int testArray[] = {5, 10, 15, 20, 25};
int testSize = sizeof(testArray) / sizeof(testArray[0]);
cout << "Original array: ";
printArray(testArray, testSize);
cout << "Sum: " << sumArray(testArray, testSize) << endl;
// Arrays are passed by pointer (can be modified)
modifyArray(testArray, testSize);
cout << "After modification: ";
printArray(testArray, testSize);
cout << endl;
// ========================================================
// PART 7: CHARACTER ARRAYS (C-STRINGS)
// ========================================================
cout << "--- PART 7: C-STYLE STRINGS ---" << endl << endl;
// Character array (C-style string)
char greeting[20] = "Hello"; // Null-terminated
char name[] = "World"; // Size is 6 (5 + null)
cout << "greeting: " << greeting << endl;
cout << "name: " << name << endl;
cout << "name size: " << sizeof(name) << " (includes null)" << endl;
// String length
cout << "Length of greeting: " << strlen(greeting) << endl;
// String copy
char dest[20];
strcpy(dest, greeting);
cout << "Copied: " << dest << endl;
// String concatenation
strcat(dest, " ");
strcat(dest, name);
cout << "Concatenated: " << dest << endl;
// String comparison
char str1[] = "apple";
char str2[] = "banana";
int cmp = strcmp(str1, str2);
cout << "strcmp(\"apple\", \"banana\"): " << cmp;
cout << " (" << (cmp < 0 ? "apple < banana" : "apple >= banana") << ")" << endl;
// Character by character
cout << "Characters in 'Hello': ";
for (int i = 0; greeting[i] != '\0'; i++) {
cout << greeting[i] << " ";
}
cout << endl;
// ⚠️ C-strings are error-prone - prefer std::string!
cout << endl;
// ========================================================
// PART 8: COMMON ARRAY PATTERNS
// ========================================================
cout << "--- PART 8: COMMON PATTERNS ---" << endl << endl;
// Count occurrences
int arr[] = {1, 2, 3, 2, 4, 2, 5};
int arrSize = sizeof(arr) / sizeof(arr[0]);
int target = 2;
int count = 0;
for (int i = 0; i < arrSize; i++) {
if (arr[i] == target) count++;
}
cout << "Occurrences of " << target << ": " << count << endl;
// Remove duplicates (requires sorting first)
int nums[] = {1, 1, 2, 2, 3, 4, 4, 5};
int numsSize = 8;
cout << "Original: ";
printArray(nums, numsSize);
// Check if array is sorted
int checkArr[] = {1, 2, 3, 4, 5};
bool isSorted = true;
for (int i = 0; i < 4; i++) {
if (checkArr[i] > checkArr[i + 1]) {
isSorted = false;
break;
}
}
cout << "Is {1,2,3,4,5} sorted? " << (isSorted ? "Yes" : "No") << endl;
cout << endl;
cout << "============================================" << endl;
cout << "ARRAY SUMMARY:" << endl;
cout << "============================================" << endl;
cout << "• Fixed size, stored contiguously" << endl;
cout << "• Zero-indexed (0 to size-1)" << endl;
cout << "• No bounds checking" << endl;
cout << "• Passed to functions by pointer" << endl;
cout << "• sizeof gives total bytes, not count" << endl;
cout << "• Use std::array or std::vector instead!" << endl;
cout << "============================================" << endl;
return 0;
}
// ============================================================
// FUNCTION DEFINITIONS
// ============================================================
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void modifyArray(int arr[], int size) {
// Arrays passed by pointer - changes affect original
for (int i = 0; i < size; i++) {
arr[i] *= 2; // Double each element
}
}
int sumArray(const int arr[], int size) {
// const prevents modification
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}
// ============================================================
// EXERCISES:
// ============================================================
/*
* 1. Write functions to:
* - Rotate array left by k positions
* - Rotate array right by k positions
* - Find second largest element
*
* 2. Implement bubble sort for an integer array
*
* 3. Create a 2D array for tic-tac-toe and functions to:
* - Display the board
* - Check for winner
* - Check for draw
*
* 4. Write a program to add two matrices
*/