Skip to content
codingdud edited this page Sep 7, 2024 · 3 revisions

This code demonstrates the basic usage of arrays in C++. It initializes an array of integers, accesses and prints its elements, and calculates its size. Additionally, it shows how to use vectors as an alternative to arrays, providing dynamic resizing and other features.

cp-question

#include <iostream>
#include <vector>

using namespace std;

int main() {
    // Declaring an array of integers
    int arr[5];

    // Initializing the array
    arr[0] = 10;
    arr[1] = 20;
    arr[2] = 30;
    arr[3] = 40;
    arr[4] = 50;

    // Accessing and printing elements of the array
    cout << "Array elements: ";
    for (int i = 0; i < 5; ++i) {
        cout << arr[i] << " ";
    }
    cout << endl;

    // Finding the size of the array
    int size = sizeof(arr) / sizeof(arr[0]);
    cout << "Size of the array: " << size << endl;

    // Creating an array using vectors
    vector<int> vec = {1, 2, 3, 4, 5};

    // Accessing and printing elements of the vector
    cout << "Vector elements: ";
    for (int i = 0; i < vec.size(); ++i) {
        cout << vec[i] << " ";
    }
    cout << endl;

    return 0;
}
Clone this wiki locally