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:

  1. We include the <iostream> library, which provides input and output functionalities in C++.

  2. We declare and initialize an integer array arr with some values.

  3. We calculate the size of the array using the sizeof operator. The sizeof(arr) gives the total size of the array in bytes, and sizeof(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.

  4. We use a for loop to iterate through each element of the array. The loop variable i starts from 0 and goes up to size - 1.

  5. 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 of arr[i] to the console.

  6. 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.