Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Loops

nested loop loop

  • Please log in to reply
1 reply to this topic

#1 johnny

johnny

    CC Lurker

  • Just Joined
  • Pip
  • 7 posts

Posted 25 February 2008 - 05:26 PM

Hello,

I'm having a little difficulty on this one:

Use nested loops that print the following pattern.
1 2 3 4 5 6 
  1 2 3 4 5 
    1 2 3 4 
      1 2 3 
        1 2 
          1 

Here's what I did:
#include <iostream> 
#include <iomanip> 
using namespace std; 

int main() 
{ 
   for (int i = 6; i >= 1; i--) 
   { 
      for (int j = 1; j <= i; j++) 
      { 
         cout << setw(3) << j; 
      } 
      cout << endl; 
   } 

   return 0; 
} 

The result was:
1 2 3 4 5 6 
1 2 3 4 5 
1 2 3 4 
1 2 3 
1 2 
1 

I want to get the 2nd through the 6th row kinda moved to right, to make it look like the one above. I'm having a difficulty rewriting the code. Can anyone help, please?



Thanks,

J.
  • 0

#2 dargueta

dargueta

    I chown trolls.

  • Moderator
  • 4854 posts
  • Programming Language:C, Java, C++, PHP, Python, JavaScript, Perl, Assembly, Bash, Others
  • Learning:Objective-C

Posted 25 February 2008 - 07:04 PM

Add spaces for each number you don't print, so at the beginning of your loop you'd have third loop that outputs a specific number of spaces like so:

for(i = 6; i >= 1; --i)
{
    //this is the loop you need to add - right-justify...
    for(n = 6 - i; n > 0; --n)
        cout << " ";
    //your other loop goes here.
}

All this does is count the number of spaces you need and prints them out one at a time. So when i = 6, 6 - 6 = 0 spaces are necessary. When i = 5, 6 -5 = 1 space is necessary. See what I mean?
  • 0





Also tagged with one or more of these keywords: nested loop, loop

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download