Arrays
In C++, an array is a collection of elements of the same data type that are stored in contiguous memory locations. Arrays are used to store multiple values of the same type and are accessed using an index.
Here's an example of declaring and accessing elements in an array:
1#include <iostream>
2using namespace std;
3
4int main() {
5 int numbers[5];
6
7 // Initialize array elements
8 numbers[0] = 1;
9 numbers[1] = 2;
10 numbers[2] = 3;
11 numbers[3] = 4;
12 numbers[4] = 5;
13
14 // Access array elements
15 cout << "Element at index 0: " << numbers[0] << endl;
16 cout << "Element at index 2: " << numbers[2] << endl;
17
18 return 0;
19}
In this example, we declare an array numbers
containing 5 elements. We then initialize the elements with values 1 to 5. Finally, we access and print the elements at index 0 and index 2.
Arrays are useful for storing and manipulating large sets of data such as financial market prices, historical stock prices, or statistical data.
Pointers
A pointer is a variable that stores the memory address of another variable. In C++, pointers are used to manage memory and enable dynamic memory allocation.
Here's an example of declaring a pointer and accessing the value it points to:
1#include <iostream>
2using namespace std;
3
4int main() {
5 int number = 10;
6 int* numberPtr;
7
8 // Assign the address of number to numberPtr
9 numberPtr = &number;
10
11 // Access the value using the pointer
12 cout << "Value of number: " << *numberPtr << endl;
13
14 return 0;
15}
In this example, we declare an integer variable number
and a pointer variable numberPtr
. We assign the address of number
to numberPtr
using the address-of operator &
. Finally, we access the value of number
using the dereference operator *
and print it.
Pointers are commonly used in finance for memory management in complex data structures and for efficient memory usage.
Arrays and pointers are fundamental concepts in C++ programming, and understanding them is crucial for working with financial data and implementing efficient algorithms.
TIP: In basketball, arrays can be related to a team roster, where each element represents a player's stats or information. Pointers can be compared to a coach's finger, pointing and accessing specific players during a game.
In the next lesson, we'll explore classes and objects in C++ and their relevance to finance.
xxxxxxxxxx
using namespace std;
int main() {
// Replace with your C++ logic here
}