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;
}

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?

Edited 4 Years Ago by Schol-R-LEA

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);
}

Edited 4 Years Ago by Lucaci Andrew

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

This question has already been answered. Start a new discussion instead.