How to Print an Array in C++?
In C++, an array is a fixed-size linear data structure that stores a collection of elements of the same type in contiguous memory locations. In this article, we will learn how to print an array in C++.
For Example,
Input:
array = {10, 20, 30, 40, 50}
Output:
Array Elements: 10 20 30 40 50
Printing Array Elements in C++
To print array elements in C++, we can use a simple for loop to iterate over the elements of the array and print each element while iterating. This allows us to print the whole array without using a single statement for printing single element.
C++ Program to Print an Array C++
The below program demonstrates how we can use a simple for loop to iterate over the array elements and print each one.
// C++ program to print an array
#include <iostream>
using namespace std;
int main()
{
// Intializing an Array
int array[] = { 10, 20, 30, 40, 50 };
// finding size of array
int n = sizeof(array) / sizeof(array[0]);
// Print the array
cout << "Array Elements: ";
for (int i = 0; i < n; i++)
cout << array[i] << " ";
cout << endl;
return 0;
}
Output
Array Elements: 10 20 30 40 50
Time Complexity: O(N), where N is the size of the array.
Auxilliary Space: O(1)
Note: We can also use range based for loop in C++11 and later to iterate through the array and print each element.