How Can I Convert a Nested For Loop to a Do-While Loop in C++?

  • Thread starter Thread starter magnifik
  • Start date Start date
  • Tags Tags
    Loops Product
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 2K views
magnifik
Messages
350
Reaction score
0
I am trying to create a code that does the exact same thing as this does
Code:
#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 << "#\n";
	    }
	}

but using a do while loop instead. what i have so far is this

Code:
#include <iostream>
	using namespace std;

	int main()
	{
	    int len;

	    cout << "Enter a number: ";
	    cin >> len;
			
	    for (int i = 0; i < len; i++)
	    {
			int j = i+1;
			do
			{
				cout << ' ';
				j++;
			}
		while (j < len);
		cout << "#\n";
		}
	}

the only problem is on the last line the "#" signs line up instead of being diagonal. any help on how to fix this??
 
Physics news on Phys.org
try put a if condition insdie the do while loop instead just count outside while loop. could use conditions like if j = len -1, then count the #
 
kentigens said:
try put a if condition insdie the do while loop instead just cout outside while loop. could use conditions like if j = len -1, then cout the #

hmm, not exactly sure what you mean. the closest i got was adding

Code:
 if (j == len -1) {
           cout << "#";
           }
into the do part of the do while loop, but this just created two side by side diagonal lines :T to top line had len - 1, but the bottom line had the correct shape and number. any idea on how to get rid of the first one?
 
i mean to take out the line where u count the # from ur original code. and btw, don't have vs here, so can't really run ur code. can u please post up the outputs? both original code and the one u have atm?