1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Same product, different loops

  1. Apr 11, 2010 #1
    I am trying to create a code that does the exact same thing as this does
    Code (Text):
    #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 (Text):
    #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??
     
  2. jcsd
  3. Apr 11, 2010 #2
    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 #
     
  4. Apr 11, 2010 #3
    hmm, not exactly sure what you mean. the closest i got was adding

    Code (Text):
     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?
     
  5. Apr 19, 2010 #4
    i mean to take out the line where u cout the # from ur original code. and btw, dont have vs here, so cant really run ur code. can u plz post up the outputs? both original code and the one u have atm?
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook