Reputation: 85
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
Reputation: 64
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
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
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