In this C++ tutorial, you will learn how to print elements of a vector, using looping statements like While loop, For loop, or Foreach loop, with examples.

C++ Print Vector Elements

To print elements of C++ vector, you can use any of the looping statements or foreach statement.

1. Print vector elements using ForEach

In the following program, we shall use C++ Foreach statement to print the elements of vector.

C++ Program

</>
Copy
#include <iostream>
#include <vector>
using namespace std;

int main() {
   vector<int> nums;
   nums.push_back(53);
   nums.push_back(47);
   nums.push_back(85);
   nums.push_back(92);

   for (int element: nums)
      cout << element << endl;
}

Output

53
47
85
92

2. Print vector elements using While loop

In the following program, we shall use C++ While Loop to print the elements of vector from starting to end. We shall use index to access an element of vector during each iteration.

C++ Program

</>
Copy
#include <iostream>
#include <vector>
using namespace std;

int main() {
   vector<int> nums;
   nums.push_back(53);
   nums.push_back(47);
   nums.push_back(85);
   nums.push_back(92);

   int i = 0;
   while (i < nums.size()) {
      cout << nums[i] << endl;
      i++;
   }     
}

Output

53
47
85
92

3. Print vector elements using For loop

In the following program, we shall use C++ For Loop to print the elements of vector. As in while loop, we shall use index to access elements of vector in this example as well.

C++ Program

</>
Copy
#include <iostream>
#include <vector>
using namespace std;

int main() {
   vector<int> nums;
   nums.push_back(53);
   nums.push_back(47);
   nums.push_back(85);
   nums.push_back(92);

   for (int i = 0; i < nums.size(); i++) {
      cout << nums[i] << endl;
   }     
}

Output

53
47
85
92

Conclusion

In this C++ Tutorial, we learned how to print all the elements of a vector from start to end using loop statements and foreach statement.