Turning a for loop to a do-while loop?

Hello, how can I change my for loop to a while loop? I am currently on the right path I think but the first 2 iterations are not printing the correct output.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
  #include <iostream>
using namespace std;

int main()
{
	int len;

	cout << "Enter a number: ";
	cin >> len;

	for (int i = 0; i < len; i++)
	{
		for (int j = i + 1; j < len; j++)
		{
			cout << " ";
		}
		cout << "#" << endl;
	}
}

#include<iostream>
using namespace std;

int main() 
{
	int len;

	cout << "Enter a number: ";
	cin >> len;
	int i = 0;

	do
	{  
		if (len < 0)
			break; 
		int j = i + 1;
	    do {
			cout << " ";
			j++;
           } while (j < len);
		   cout << "#" << endl;
		   i++;
	}while (i < len);
		
}
     
Last edited on
All you need is a simple fix on line 40: (edit underlined)
39
40
41
    ...
    } while (j <= len);
    ...


Hope this helped,
VX
Last edited on
OMG thank you so much, I was stuck on that for a long time.
No problem! Glad to help! :)

-VX
A bigger question is why you want to do this? IMO it just makes the code messier.

I find there very few situations where a do loop is actually required. It's possible to convert from any of the 3 loop statements, to any of the others. So that often means one can convert a do loop into a while loop.

for loops are good when one knows exactly how many times to loop. while loops are good when one simply has an end condition.

Just because a do loop always executes once is not sufficient reason on it's own to use them.
Topic archived. No new replies allowed.