As a C++ developer, working with arrays is an integral part of the job. Arrays allow you to store multiple values of the same data type and access them easily. However, printing arrays for debugging or output purposes can be tricky if you don‘t fully understand the syntax.
In this comprehensive guide, we will walk through everything you need to know about printing arrays in C++, from basic printing to multi-dimensional arrays. By the end, you‘ll have the knowledge to print arrays confidently in any scenario.
What is an Array?
Before we dive into printing arrays, let‘s briefly go over what exactly an array is in C++.
An array is a collection of elements of the same data type placed in contiguous memory locations. This allows for easy access and manipulation. The elements are identified by an index, starting from 0.
For example, if we had an array called nums
with 5 integer elements, it would look conceptually like this:
nums: [15, 22, 16, 44, 33]
Index: 0 1 2 3 4
The key things to know about C++ arrays:
- They contain elements of the same data type – can‘t mix types
- The elements occupy contiguous memory locations
- Elements are indexed starting from 0
- Array size must be declared ahead of time
Keeping this overview of arrays in mind will help understand the specifics of printing them.
Printing a Basic Array
Let‘s start by looking at how to print a simple one-dimensional array of integers.
Here is an example array with 5 elements:
int arr[5] = {3, 5, 2, 9, 7};
To print this array, we loop through each index and access the element using []:
#include <iostream>
using namespace std;
int main() {
int arr[5] = {3, 5, 2, 9, 7};
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
return 0;
}
// Output: 3 5 2 9 7
By looping 0 through 4, we can access each array index and print the element out. The space after the element prints a space in between each element.
Let‘s break down the key parts:
Array Declaration:
int arr[5] = {3, 5, 2, 9, 7};
This declares an integer array named arr
with 5 elements and initializes values.
Print Loop:
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
This loops through the array index starting from 0 to the last index 4, accesses each element using arr[i]
, prints it out, and prints a space after each element.
The output is each element printed with spaces between.
This is the simplest way to print an array in C++. Now let‘s expand on this concept.
Printing Array Elements on Separate Lines
Having all array elements print on one line works but can be hard to read. To print each element on its own line, we tweak our print statement:
#include <iostream>
using namespace std;
int main() {
int arr[5] = {3, 5, 2, 9, 7};
for(int i = 0; i < 5; i++){
cout << "Element " << i << ": " << arr[i] << endl;
}
return 0;
}
// Output:
// Element 0: 3
// Element 1: 5
// Element 2: 2
// Element 3: 9
// Element 4: 7
Instead of immediately printing the value, we print the index and element value, and end the line with endl
. This neatly prints each element on its own line for easy reading.
Printing Other Data Type Arrays
The examples so far have used integer arrays, but you can print arrays of other data types too.
Here is an example printing a double
array:
#include <iostream>
using namespace std;
int main() {
double expenses[5] = {12.99, 8.75, 21.33, 19.05, 14.72};
for(int i = 0; i < 5; i++){
cout << "Expense " << i << ": $" << expenses[i] << endl;
}
return 0;
}
// Output:
// Expense 0: $12.99
// Expense 1: $8.75
// Expense 2: $21.33
// Expense 3: $19.05
// Expense 4: $14.72
The process is the exact same, the only thing that changes is declaring expenses
as a double
array and printing a $
before the value.
This concept applies to any data type like string
, char
, custom objects, etc. The syntax for printing stays exactly the same – loop through and print each index.
Printing Contents of a C-Style Array
In addition to arrays declared with a size like int arr[5]
, C++ supports C-style arrays where no array size is provided.
These arrays allocate as much memory needed to store the initialized elements. Since no size is explicitly given, we‘ll use sizeof()
to determine the number of elements.
Here is an example C-style array:
#include <iostream>
using namespace std;
int main() {
int prices[] = {10, 7, 13, 19};
int size = sizeof(prices) / sizeof(prices[0]);
for(int i = 0; i < size; i++){
cout << "Price " << i << ": $" << prices[i] << endl;
}
return 0;
}
// Output:
// Price 0: $10
// Price 1: $7
// Price 2: $13
// Price 3: $19
Some key points on C-style arrays:
prices
array is declared without an explicit sizesizeof(prices)
gives the total bytes allocatedsizeof(prices[0])
gives bytes per element- Calculate elements with:
total_bytes / bytes_per_element
- Print loop limits by this calculated size
Using C-style arrays combines flexibility of not pre-declaring a size with ability still loop through and print the contents.
Printing a Subsection of an Array
Sometimes you only want to print a portion of an array. Using a slightly modified loop range allows you to print any subsection.
For example:
#include <iostream>
using namespace std;
int main() {
string letters[10] = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"};
// Print letters 3 through 7
for(int i = 3; i <= 7; i++){
cout << letters[i] << " ";
}
return 0;
}
// Output: d e f g h
By changing our loop start point (i = 3
) and end point (i <= 7
), we print just indexes 3 through 7 inclusive.
This idea can apply to print the first and last few elements, print alternate elements, and more.
Printing Array Contents Backwards
To print an array backwards from end to beginning, we loop from the last index down to 0.
For example:
#include <iostream>
using namespace std;
int main() {
int scores[10] = {90, 67, 84, 76, 92, 57, 83, 94, 61, 79};
for(int i = 9; i >= 0; i--){
cout << scores[i] << " ";
}
return 0;
}
// Output: 94 83 57 92 76 84 67 90 61 79
By starting i
at the last index 9 and working down with i--
, we read the array in reverse order.
Printing a String Array
Arrays of C++ strings work the same way as other data types – we just have to deal with strings instead of primitives.
#include <iostream>
using namespace std;
int main() {
string names[4] = {"John", "Aliya", "Dave", "Sophia"};
for(int i = 0; i < 4; i++) {
cout << names[i] << endl;
}
return 0;
}
// Output:
// John
// Aliya
// Dave
// Sophia
The print loop logic stays identical. The only difference with strings is that printing newlines makes it easy to distinguish each string element.
Printing 2D Arrays
Moving from 1D to 2D arrays brings some added complexity but printing follows similar logic – just with nested loops.
Here is how to print a basic 2D integer array:
#include <iostream>
using namespace std;
int main() {
int grid[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
cout << grid[i][j] << " ";
}
cout << endl;
}
return 0;
}
// Output:
// 1 2 3
// 4 5 6
// 7 8 9
By nesting two for
loops, we can iterate through both the rows (outer loop) and columns (inner loop) to access each element.
Printing each row on its own line keeps the formatting aligned.
Let‘s walk through the key parts:
2D Array Initialization
int grid[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
This creates a 3×3 integer grid initialized to these values.
Nested Print Loops
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
cout << grid[i][j] << " ";
}
cout << endl;
}
- Outer loop index
i
goes through each row - Inner loop index
j
prints each column element in that row endl
starts new line per row
Printing 2D arrays applies the same logic extending to arrays with higher dimensionality.
Printing Jagged Arrays
Jagged arrays contain rows that can be different lengths. This makes printing slightly more complex.
Here is printing a jagged 2D string array:
#include <iostream>
using namespace std;
int main() {
string jagged[3][3] = {{"A", "B", "C"}, {"D", "E"}, {"F"}};
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
if(jagged[i][j] != "") {
cout << jagged[i][j] << " ";
} else {
break;
}
}
cout << endl;
}
return 0;
}
// Output:
// A B C
// D E
// F
The key difference is that we have to check if an element exists before printing since rows can be shorter. The break
exits the inner loop to not print extra blanks.
Handling uneven row lengths takes a bit more finesse when printing jagged arrays!
Passing Arrays to Functions
Often you will want to pass arrays to reusable functions for printing instead of printing directly in main()
.
Here is an example of a print()
function:
#include <iostream>
using namespace std;
// Print array contents
void print(int arr[], int size) {
for(int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int nums[] = {5, 9, 1, 8, 2};
print(nums, 5);
return 0;
}
// Output: 5 9 1 8 2
Notes on passing arrays to functions:
- Declare parameter as pointer
int* arr
- Specify array size as additional parameter
- Access elements with indexes like normal
- Pass array by name without brackets
Being able to reuse print functions makes code more organized and maintainable.
Optimizing Array Printing
Certain optimizations can speed up printing performance when working with large arrays:
Bounds Checking
Verifying array indexes stay in bounds is slower but safer:
if(i < size && i >= 0) {
// Print element
}
Pre-incrementing
Use i++
instead of i--
if iterating forward:
for(int i = 0; i < max; i++) {
// Print element
}
Iterator Alternative
Use iterators for potentially faster traversal:
vector<int> vec{1, 2, 3};
for(auto it = vec.begin(); it != vec.end(); ++it) {
// Print element
}
Applying optimizations like these can provide better performance printing arrays in production systems.
C++ Array Printing Compared to Other Languages
It can be useful to contrast C++ array printing syntax with other popular languages:
Java
Java array printing works identical to C++ with basic for loops:
int[] numbers = {2, 4, 6, 8};
for(int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Python
Python directly prints arrays without needing explicit loops:
numbers = [5, 10, 15]
print(numbers)
# [5, 10, 15]
This demonstrates Python‘s increased brevity and high-level orientation.
JavaScript
JavaScript array methods like forEach
abstract away the implementation:
let colors = ["red", "blue", "green"];
colors.forEach(color => console.log(color));
Understanding syntax variations across languages illustrates their unique approaches.
Conclusion
Being able to accurately print array contents is a key programming skill that takes practice to master. From basic print loops to multi-dimensional arrays, properly accessing elements helps in all development stages.
Use this guide as a C++ array printing reference anytime you need to display contents while coding or debugging. It summarizes all fundamental to advanced techniques for printing single and multi-dimensional arrays adapted to a wide range of scenarios you may encounter.
Complement fundamental language knowledge by learning specialized skills like properly printing arrays. This will turn you from a novice into an expert C++ programmer that writes optimized code.