Vectors in R:
In R, a vector is a one-dimensional array that can store various types of data, such as numeric values, characters, or logical values. Think of it as a simple tool for organizing and managing data. Here are some key points:
- Creating Vectors in R:
- You create a vector using the
c()
function. - Elements are separated by commas within the parentheses.
- For example:
my_vector <- c(1, 5, 2, 0)
- You create a vector using the
- Dynamic Resizing:
- Vectors automatically resize themselves when elements are added or removed.
- This dynamic behavior makes them convenient for handling collections of data.
- Homogeneous Data:
- All elements in a vector must be of the same data type.
- You can’t mix different types (e.g., numbers and characters) in the same vector.
Arrays in C++:
In C++, an array is a fixed-size collection of elements of the same data type. Arrays provide a way to store multiple values of the same type in contiguous memory locations. Here’s how you can work with arrays:
- Creating Arrays:
- Declare an array with a specific size and data type.
- For example:
const int size = 5; int myArray[size] = {10, 20, 30, 40, 50};
- Accessing Elements:
- Use index notation (starting from 0) to access individual elements.
- For example:
cout << "First element: " << myArray[0] << endl;
- Modifying Elements:
- You can modify array elements directly:
myArray[1] = 25;
- You can modify array elements directly:
- Looping Through the Array:
- Use loops (e.g.,
for
loop) to iterate through the array:for (int i = 0; i < size; ++i) { cout << myArray[i] << " "; }
- Use loops (e.g.,
Arrays are powerful tools for managing data efficiently, especially when you know the size in advance.
Example: Sum of Array Elements
Let’s calculate the sum of elements in myArray
:
#include <iostream>using namespace std; int main() { const int size = 5; int myArray[size] = {10, 20, 30, 40, 50}; int sum = 0; for (int i = 0; i < size; ++i) { sum += myArray[i]; } cout << "Sum of array elements: " << sum << endl; return 0; }