Introduction To Vectors In Arrays

by

Last updated on Aug 17, 2024
Data Structure - Introductory Part

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:

  1. 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)
  2. Dynamic Resizing:
    • Vectors automatically resize themselves when elements are added or removed.
    • This dynamic behavior makes them convenient for handling collections of data.
  3. 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:

  1. 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};
  2. Accessing Elements:
    • Use index notation (starting from 0) to access individual elements.
    • For example: cout << "First element: " << myArray[0] << endl;
  3. Modifying Elements:
    • You can modify array elements directly: myArray[1] = 25;
  4. 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] << " "; }

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;
}

How useful was this post?

5 star mean very useful & 1 star means not useful at all.

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Tags:

Data Structure

Unit 1: Growth of Functions, Recurrence Relations

Unit 2: Arrays, Linked Lists, Stacks, Queues, Deques

Unit 3: Recursion

Unit 4: Trees, Binary Trees

Unit 5: Binary Search Trees, Balanced Search Trees

Unit 6: Binary Heap, Priority Queue

Unit 7: Graph Representations and Traversal Algorithms