Advertisement
Guest User

Nesting Loops

a guest
May 22nd, 2015
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. /*
  2. For the pyramid design, try to find a relation between the pattern and the line number.
  3. For example,
  4. if you need to print this:
  5.  
  6.     *
  7.     **
  8.     ***
  9.     ****
  10.     *****
  11.  
  12. Then notice that the number of stars on each line is equal to the line number.
  13. So we need two FOR loops: one to switch the lines and another to print the stars,
  14. We nest the loops because for each line, we need a loop to count till the line number (for the number of stars)
  15. and after this job of printing the stars for a particular line completes, we move on to the next line. (After cout-ing a newline character, notice that we don't want this newline character in the inner loop as we don't want a new line after every star, so we put the newline OUTSIDE THE INNER LOOP BUT INSIDE THE OUTER LOOP)
  16. This continues till we reach the end of the number of lines we want.
  17.  
  18. The only thing to remember in nesting loops is, try to find a similarity in the lines (again, here the symmetry is that the number of stars is equal to the line number.)
  19. */
  20.  
  21. #include <iostream>
  22. using namespace std;
  23.  
  24. int main()
  25. {
  26.     int n; 
  27.     cout << "Enter number of lines: ";
  28.     cin >> n;  
  29.  
  30.     for (int i=1; i<=n; i++)                // We need to repeat a process n times
  31.     {
  32.         for (int j=1; j<=i; j++)            // Print a star i number of times
  33.         {
  34.             cout << "*";
  35.         }
  36.         cout << "\n";                   // Move to a new line
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement