Space at the end of my for loop.

i notice that in my for loop that prints out the values and a space between them, is adding an additional space and the end of the last number it prints out. How do i prevent this once number 9 is done printing?



1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

using namespace std;

int main() {
	
	int arr[10];
	
	for (int i = 0; i < 10; i++)
	    arr[i] = i;
	for (int i = 0; i < 10; i++)
	    cout<<arr[i]<<" ";
	    
}
Last edited on
1
2
3
4
    cout << arr[0];
    for (int i = 1; i < 10; i++)
        cout << ' ' << arr[i];
    cout << '\n';

would that work, i was thinking of this type of logic. is this to complex?

1
2
3
4
	    if (i == 10 - 1)
	    cout<<endl;
	    else
	        cout<<" ";
No, that'll work fine, too. Both add about the same amount of complexity, and will probably optimized into about the same thing. Personally, I'd probably prefer tpb's solution though (wrapped in a function that can handle an empty array).
Last edited on
As Ganado mentioned, what I showed doesn't handle a totally empty array and it should be in a function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

template <typename T>
void printArray(std::ostream& os, const T* a, size_t sz,
                const char *delim=" ", const char *end="\n")
{
    if (sz > 0) {
        std::cout << a[0];
        for (std::size_t i = 1; i < sz; i++)
            std::cout << delim << a[i];
    }
    std::cout << end;
}

int main() {
    using std::cout;
    int a[] = {1, 2, 3, 4};
    size_t sz = sizeof a / sizeof *a;
    printArray(cout, a, sz);
    printArray(cout, a, sz, " ", " :: ");
    printArray(cout, a, sz, ", ");
    printArray(cout, a, sz, "\n", "\n\n");
}

@tbp, good solution, although I think you should #include <cstddef> when using std::size_t (even though it is made available by #include <iostream> ). Also, I think you forgot to write the std namespace for std::size_t for the sz parameter, and the local variable in main.
Topic archived. No new replies allowed.