Mark As Completed Discussion

Arrays and vectors are important data structures in C++ that allow you to store and manipulate collections of elements. They are useful when you need to work with multiple values of the same type.

In C++, arrays are fixed-size containers that hold a specific number of elements. You can access and modify array elements using their indices, which start from 0.

Here's an example of declaring and accessing elements in an array:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5  // Declare an array
6  int arr[5] = {1, 2, 3, 4, 5};
7
8  // Accessing array elements
9  cout << "First element: " << arr[0] << endl;
10  cout << "Third element: " << arr[2] << endl;
11
12  // Modify array elements
13  arr[1] = 10;
14  cout << "Modified second element: " << arr[1] << endl;
15
16  return 0;
17}

Output:

SNIPPET
1First element: 1
2Third element: 3
3Modified second element: 10

Vectors, on the other hand, are dynamic arrays that can grow or shrink in size at runtime. They provide more flexibility compared to fixed-size arrays.

Here's an example of declaring and accessing elements in a vector:

TEXT/X-C++SRC
1#include <iostream>
2#include <vector>
3
4using namespace std;
5
6int main() {
7  // Declare and initialize a vector
8  vector<int> vec = {1, 2, 3, 4, 5};
9
10  // Accessing vector elements
11  cout << "First element: " << vec[0] << endl;
12  cout << "Third element: " << vec[2] << endl;
13
14  // Modify vector elements
15  vec[1] = 10;
16  cout << "Modified second element: " << vec[1] << endl;
17
18  return 0;
19}

Output:

SNIPPET
1First element: 1
2Third element: 3
3Modified second element: 10

Arrays and vectors are fundamental in C++ programming and are widely used to solve various programming problems.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment