0% found this document useful (0 votes)
0 views6 pages

CPP Array Notes

This comprehensive study guide covers C++ arrays and fundamental algorithms, detailing operations such as calculating array size, iteration techniques, searching, sorting, and working with multi-dimensional arrays. Key concepts include the use of the sizeof() operator, traditional and range-based loops, passing arrays to functions, linear search, bubble sort, and dynamic user input. The guide also provides code examples and a quick reference summary for essential syntax and notes.

Uploaded by

suyash162534
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views6 pages

CPP Array Notes

This comprehensive study guide covers C++ arrays and fundamental algorithms, detailing operations such as calculating array size, iteration techniques, searching, sorting, and working with multi-dimensional arrays. Key concepts include the use of the sizeof() operator, traditional and range-based loops, passing arrays to functions, linear search, bubble sort, and dynamic user input. The guide also provides code examples and a quick reference summary for essential syntax and notes.

Uploaded by

suyash162534
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

COMPREHENSIVE STUDY GUIDE

C++ Arrays & Fundamental Algorithms


A detailed technical breakdown of array operations, memory size calculations, iteration techniques,
searching, sorting, and multi-dimensional arrays in C++.

1. The sizeof() Operator & Calculating Array Size

The sizeof() operator determines the size in bytes of a variable, data type, class, or array. Since
standard C++ raw arrays do not natively store their length, computing the number of elements requires
dividing the total size of the array by the size of a single element.

Formula for Array Length


int numElements = sizeof(array) / sizeof(array[0]);

// Example: Calculating size in bytes and number of elements


#include <iostream>

int main() {
std::string name = "Bro Code";
double gpa = 2.5;
char grade = 'F';
bool student = true;
char grades[] = {'A', 'B', 'C', 'D', 'F'};
std::string students[] = {"Spongebob", "Patrick", "Squidward", "Sandy"};

std::cout << sizeof(name) << " bytes


";
std::cout << sizeof(students) / sizeof(std::string) << " elements
";

return 0;
}

2. Array Iteration: Traditional vs Range-Based (Foreach) Loops

Iterating over an array can be achieved using traditional index-based for loops or range-based for loops
introduced in C++11.

A. Index-Based For Loop

Allows access to the current index, which is essential when index tracking or modification is required.

C++ Programming Notes — Arrays & Algorithms Page 1 of 6


#include <iostream>

int main() {
char grades[] = {'A', 'B', 'C', 'D', 'F'};

for(int i = 0; i < sizeof(grades)/sizeof(grades[0]); i++){


std::cout << grades[i] << '
';
}

return 0;
}

B. Range-Based For Loop (Foreach)

Provides a cleaner, less error-prone syntax when simply traversing through all elements sequentially.

#include <iostream>

int main() {
// foreach loop = loop that eases traversal over an iterable dataset
int grades[] = {65, 72, 81, 93};

for(int grade : grades){


std::cout << grade << '
';
}

return 0;
}

3. Passing Arrays to Functions

When an array is passed to a function, it decays into a pointer pointing to its first element. Consequently, the
function loses knowledge of the array's original size. Therefore, the array size must be passed as an
explicit parameter.

#include <iostream>

double getTotal(double prices[], int size);

int main() {
double prices[] = {49.99, 15.05, 75.00, 9.99};
int size = sizeof(prices) / sizeof(prices[0]);
double total = getTotal(prices, size);

std::cout << "The total is: $" << total;

return 0;

C++ Programming Notes — Arrays & Algorithms Page 2 of 6


}

double getTotal(double prices[], int size) {


double total = 0;
for(int i = 0; i < size; i++){
total += prices[i];
}
return total;
}

4. Linear Search in Arrays

Linear search iterates through an array sequentially to locate a target element, returning its index if found or
-1 if the element is not present.

#include <iostream>
#include <string>

int searchArray(std::string array[], int size, std::string element);

int main() {
std::string foods[] = {"pizza", "hamburger", "hotdog"};
int size = sizeof(foods) / sizeof(foods[0]);
std::string myFood;

std::cout << "Enter element to search for:


";
std::getline(std::cin, myFood);

int index = searchArray(foods, size, myFood);

if(index != -1){
std::cout << myFood << " is at index " << index;
} else {
std::cout << myFood << " is not in the array";
}

return 0;
}

int searchArray(std::string array[], int size, std::string element) {


for(int i = 0; i < size; i++){
if(array[i] == element){
return i;
}
}
return -1;
}

C++ Programming Notes — Arrays & Algorithms Page 3 of 6


5. Sorting an Array (Bubble Sort - Descending Order)

Bubble sort repeatedly steps through the list, compares adjacent elements, and swaps them if they are in
the wrong order. The example below sorts array elements in descending order.

#include <iostream>

void sort(int array[], int size);

int main() {
int array[] = {10, 1, 9, 2, 8, 3, 7, 4, 6, 5};
int size = sizeof(array) / sizeof(array[0]);

sort(array, size);

for(int element : array){


std::cout << element << " ";
}

return 0;
}

void sort(int array[], int size){


int temp;
for(int i = 0; i < size - 1; i++){
for(int j = 0; j < size - i - 1; j++){
if(array[j] < array[j + 1]){ // Change to '>' for ascending order
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}

6. Memory Filling with std::fill()

The std::fill() function assigns a specific value to a range of elements defined by begin and end
iterators/pointers.

#include <iostream>

int main() {
// std::fill(begin, end, value)
const int SIZE = 99;
std::string foods[SIZE];

// Filling array in three equal segments


fill(foods, foods + (SIZE/3), "pizza");

C++ Programming Notes — Arrays & Algorithms Page 4 of 6


fill(foods + (SIZE/3), foods + (SIZE/3)*2, "hamburger");
fill(foods + (SIZE/3)*2, foods + SIZE, "hotdog");

for(std::string food : foods){


std::cout << food << '
';
}

return 0;
}

7. Dynamic User Input into Fixed-Sized Arrays

Accepting user input into an array until a sentinel value (e.g., 'q' ) is entered or the array capacity is
reached.

#include <iostream>
#include <string>

int main() {
std::string foods[5];
int size = sizeof(foods) / sizeof(foods[0]);
std::string temp;

for(int i = 0; i < size; i++){


std::cout << "Enter in food you like or 'q' to quit #" << i + 1 << ": ";
std::getline(std::cin, temp);
if(temp == "q"){
break;
} else {
foods[i] = temp;
}
}

std::cout << "


You like the following food:
";

// Iterates until an empty element is encountered


for(int i = 0; !foods[i].empty(); i++){
std::cout << foods[i] << '
';
}

return 0;
}

C++ Programming Notes — Arrays & Algorithms Page 5 of 6


8. Multidimensional Arrays (2D Grid Traversal)

A two-dimensional array represents data in a grid/matrix format of rows and columns. Nested loops are used
to traverse elements.

#include <iostream>

int main() {
std::string cars[][3] = {
{"Mustang", "Escape", "F-150"},
{"Corvette", "Equinox", "Silverado"},
{"Challenger", "Durango", "Ram 1500"}
};

int rows = sizeof(cars) / sizeof(cars[0]);


int columns = sizeof(cars[0]) / sizeof(cars[0][0]);

for(int i = 0; i < rows; i++){


for(int j = 0; j < columns; j++){
std::cout << cars[i][j] << " ";
}
std::cout << '
';
}

return 0;
}

9. Quick Reference Summary

Concept Key Syntax / Snippet Notes

Computes total element count in raw


Array Size sizeof(arr) / sizeof(arr[0])
arrays.

Foreach Loop for(type elem : array) Simplifies read-only array traversal.

Passing to Arrays decay to pointers; pass size


void fn(type arr[], int size)
Functions separately.

Range Fill fill(start, end, val) Utility function to populate array ranges.

2D Array Rows sizeof(arr) / sizeof(arr[0]) Calculates number of rows in matrix.

sizeof(arr[0]) / sizeof(arr[0]
2D Array Cols Calculates number of columns per row.
[0])

C++ Programming Notes — Arrays & Algorithms Page 6 of 6

You might also like