How to Print a Vector in C++ with a Loop (Step-by-Step Guide for Beginners)

🌟 Exploring C++ Step by Step: Printing a Vector with Style

Whether you're just diving into C++ or brushing up on some fundamentals, this simple code snippet is a great example of using standard libraries, vectors, strings, and loops. Let's walk through it together and understand each piece!

🧠 The Goal

We want to:

  • Store a set of numbers in a vector.
  • Store a message in a string.
  • Print the message followed by the vector's contents, formatted nicely with commas.

🧱 The Building Blocks

#include <vector>
#include <string>
#include <iostream>

Here we include three standard C++ headers:

  • #include <vector> – For the std::vector class.
  • #include <string> – For std::string.
  • #include <iostream> – For std::cout.

πŸš€ Main Function

int main() {

All C++ programs start from the main() function. This is where your program begins executing.

Advertisements

πŸ“¦ Declaring and Initializing Variables

const std::vector<int> x{1, 2, 3};
const std::string s{"This is a vector:"};
  • x is a vector of integers initialized with {1, 2, 3}.
  • s is a string containing the message to print.

πŸ–¨οΈ Outputting the Message

std::cout << s << " ";

This prints the message string followed by a space.

πŸ” Looping Through the Vector

for (size_t i = 0; i < x.size(); ++i) {
    std::cout << x[i];
    if (i < x.size() - 1) {
        std::cout << ", ";
    }
}

We loop through each element of the vector:

  • size_t is a safe type for indexing.
  • Each element is printed followed by a comma unless it's the last element.

βœ… Final Touch

std::cout << '\n';

This moves the cursor to the next line after printing the vector.

πŸ”š And We're Done

return 0;
}

This signals that the program completed successfully.

πŸ–₯️ Output

This is a vector: 1, 2, 3
Advertisements

Here the result:

#include <vector>
#include <string>
#include <iostream>

int main() {
    const std::vector<int> x{1, 2, 3};
    const std::string s{"This is a vector:"};

    std::cout << s << " ";
    for (size_t i = 0; i < x.size(); ++i) {
        std::cout << x[i];
        if (i < x.size() - 1) {
            std::cout << ", ";
        }
    }
    std::cout << '\n';

    return 0;
}

🧩 Final Thoughts

This snippet demonstrates good C++ practices like:

  • Using const for safety.
  • Looping through data structures instead of hardcoding output.
  • Clean and user-friendly formatting.

If you are a complete C++ beginner check this post out on how to set up C++ in Visual Studio Code.

Happy coding! ✨

Leave a Reply

Discover more from Cenk Yildiran

Subscribe now to keep reading and get access to the full archive.

Continue reading