print array elements with space c++
To print array elements with spaces in C++, you can use a loop to iterate through each element of the array and print it followed by a space. Here's an example:
#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;
}
Explanation:
- We include the
<iostream>
header file to use thestd::cout
object, which is used for standard output. - We declare an array
arr
and initialize it with some elements. - We calculate the size of the array by dividing the total size of the array by the size of one element. This gives us the number of elements in the array.
- We use a
for
loop to iterate through each element of the array. - Inside the loop, we print each element using
std::cout
followed by a space. - Finally, we return 0 to indicate successful execution of the program.
This code will output: 1 2 3 4 5
. Each element of the array is printed followed by a space.