0

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;
}
6
Contributors
7
Replies
9
Views
4 Years
Discussion Span
Last Post by new_developer
1

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 by Schol-R-LEA

0

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

1

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 by Lucaci Andrew

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.