sdev
sdev

Reputation: 85

How do I remove extra line at the end of my nested for loop?

With input 2, my code outputs:

0
 1
  2
(whitespace)

I have tried changing my loop conditions but I'm confused.

I want to remove the whitespace, here is my code:


using namespace std;

int main()
{

    int userNum;
    int i;
    int j;

    cin >> userNum;

    char space = ' ';

    for (i = 0; i <= userNum; i++)
    {
        cout << i << endl;
        for (j = 0; j <= i; j++)
        {
            cout << space;
        }
    }
}

Upvotes: 1

Views: 562

Answers (3)

all you need is to move cout code in the first for loop, after nested for loop:

for (i = 0; i <= userNum; i++)
{
    for (j = 0; j <= i; j++)
    {
        cout << space;
    }
    cout << i << endl;
}

Upvotes: 0

Nitish Gupta
Nitish Gupta

Reputation: 39

Assuming you want to print n spaces before the nth occurrence, modify the for loop as

for (i = 0; i <= userNum; i++)
    {
        for (j = 0; j < i; j++)
        {
            cout << space;
        }
        cout << i << endl;
    }

Upvotes: 3

silverfox
silverfox

Reputation: 1662

If you want to remove that pesky line down there, you could use a condition:

#include <iostream>
using namespace std;

int main()
{

    int userNum;
    int i;
    int j;

    cin >> userNum;

    char space = ' ';

    for (i = 0; i <= userNum; i++)
    {
        for (j = 0; j < i; j++)
        {
            cout << space;
        }
        cout << i;
        if (i != userNum) {cout << endl;} //only go to next line if not reached final line

    }
}

Output:

4
0
 1
  2
   3
    4

Upvotes: 0

Related Questions