Hello everyone !
I want to get output in C++ in same line. The following code gives me output in separate line.

for(int i=0; i<=10; i++)
{
    cout << i <<" " <<endl;
}

Recommended Answers

The endl manipulator has the effect of forcing a newline. If you remove it from the output line, and put it after the end of the loop, it should give the desired result:

for(int i=0; i <= 10; i++)
{
    cout << i;
    if (i < …
Jump to Post

If you want it all in one line, don't output an endl every trip through the loop.

cout << i <<" ";
Jump to Post

All 7 Replies

The endl manipulator has the effect of forcing a newline. If you remove it from the output line, and put it after the end of the loop, it should give the desired result:

for(int i=0; i <= 10; i++)
{
    cout << i;
    if (i < 10)
    {
        cout << " ";
    }
}
cout << endl;

Note that I added a test on the value of i so that it doesn't include the space after the last number; this might not be particularly important here, but it could come up under other circumstances where you wouldn't want a trailing space at the end of the line..

Any questions?

If you want it all in one line, don't output an endl every trip through the loop.

cout << i <<" ";

I think END keyword will finsih the line and bring the next output in the next line so avoid the keyword.

Remove the endl after the cout expresion inside the for.
The for statement will print out i and the new line every time it pharshes through the conditions.
Use like:

for (int i=0;i<n;i++)
    cout<<i<<" ";
cout<<"\n"; // or cout<<endl;

or as Schol-R-LEA stated, if you don't want the extra space:

#include <iostream>
using namespace std;
int main(){
    int n=10;
    for (int i=0;i<n;i++){
        if (i<=n-2) cout<<i<<" ";
        else cout<<i<<endl;
    }
    return (0);
}

I think END keyword will finsih the line and bring the next output in the next line so avoid the keyword.

Not quite. endl will. Alternate is to use ends to avoid the newline

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.