• Register
search
Log In

 

An array is a collection of elements of the same type. We can define five values of int type as an array without having to declare five different variables.

If we print the array using operator cout then we will get a random thing which won't be similar to your array. So we have to print the array in different ways. But how to print the data of an array? In this article, we are going to learn how to print an array in C++

Methods

There are different methods to print arrays, all the methods are given ahead.

 

  • Using Array Indices

The simple method to print data from an array is by iterating over the elements and print each element.

#include <iostream>

// Print contents of an array in C++ using array indices
int main()
{
	int input[] = { 1, 2, 3, 4, 5 };
	size_t n = sizeof(input)/sizeof(input[0]);

	// loop through the elements of the array
	for (size_t i = 0; i < n; i++) {
		std::cout << input[i] << ' ';
	}

	return 0;
}
  • For loop

From C++11, the recommended method for printing the data by programmers is using the range-based for loop.

#include <iostream>

// Print contents of an array in C++ using range based for loop
int main()
{
	int input[] = { 1, 2, 3, 4, 5 };

	for (const auto& value: input) {
		std::cout << value << ' ';
	}

	return 0;
}
  • Iterators

An iterator is an object that points to some element in a range of elements. Iterators are used to traverse from one element to another and this whole process of the traverse is known as iterating.

We can also use iterators for printing the array. We have to use std::begin and std::end which was introduced in C++11. Std::begin gives an iterator to the beginning and std::end gives an iterator to one past the end of the given array. Here we are not modifying anything so we have to use std::cbegin and std::cend, they return constant iterators.

#include <iostream>

// Print contents of an array in C++ using iterators
int main()
{
	int input[] = { 1, 2, 3, 4, 5 };

	for (auto it = std::cbegin(input); it != std::cend(input); it++)
	{
		std::cout << *it << ' ';
	}

	return 0;
}
  • Std::for_each

We can also use the algorithm std::for_each. This algorithm applies the specified function on each element within the specified range defined by two iterators.

#include <iostream>
#include <vector>
#include <algorithm>

void print(const int &i) {
	std::cout << i << ' ';
}

// Print contents of an array in C++ using std::for_each
int main()
{
	int input[] = { 1, 2, 3, 4, 5 };

	std::for_each(std::begin(input), std::end(input), print);

	return 0;
}

 

posted Jun 3 in c++ 100 points