how to print an array in cpp in single line
To print an array in C++ in a single line, you can use a loop to iterate through the elements of the array and print each element separated by a space.
Here is an example code snippet that demonstrates how to achieve this:
#include <iostream>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
return 0;
}
Let's break down the code and explain each step:
We include the
<iostream>
library, which provides input and output functionalities in C++.We declare and initialize an integer array
arr
with some values.We calculate the size of the array using the
sizeof
operator. Thesizeof(arr)
gives the total size of the array in bytes, andsizeof(arr[0])
gives the size of a single element in the array. By dividing the total size by the size of a single element, we get the number of elements in the array.We use a
for
loop to iterate through each element of the array. The loop variablei
starts from 0 and goes up tosize - 1
.Inside the loop, we use
std::cout
to print each element of the array followed by a space. The<<
operator is used to output the value ofarr[i]
to the console.Finally, we return 0 to indicate successful execution of the program.
When you run this code, it will output the elements of the array in a single line, separated by spaces:
1 2 3 4 5
I hope this explanation helps you understand how to print an array in C++ in a single line! Let me know if you have any further questions.