-1

I'm using while loop inside for loop to repeat for loop, but it only execute one time.

I did this code:

#include<iostream>
using namespace std;
int h, rep = 0;

int main() {
    cout << "Please enter pyramid's height: ";
    cin >> h;
    cout << "Please enter Repetition Number: ";
    cin >> rep;
    for(int i = 0; i <= h; i++) {
        while(0 < rep) {
            for(int j = 0; j <= h; j++) {
                if(i >= j)
                    cout << "x ";
                else
                    cout << "  ";
            }
            rep--;
        }
        cout << endl;
    }
}
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • Have you tried running your code line-by-line in a debugger while monitoring the values of all variables, in order to determine in which line your program stops behaving as intended? If you did not try this, then you may want to read this: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/12149471) You may also want to read this: [How to debug small programs?](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Andreas Wenzel Nov 06 '22 at 22:19

1 Answers1

2
while(0<rep){

   --rep;
}

At the conclusion of this while loop rep is 0. This is what the shown code tells your computer to do, so that's what your computer does. Your computer does this because of the Golden Rule Of Computer Programming: "Your computer always does exactly what you tell it to do instead of what you want it do".

A corollary to the Golden Rule states: "your computer never does anything you never tell your computer to do". You told your computer to stop the while loop when rep reaches 0, so rep is now 0. rep will still be 0 on the second iteration of the outer loop, so when it gets to this while loop, the second time, rep is still 0. You never told your computer to reset rep to the original value it had before the while loop, so your computer never does that.

If you would like for rep to be reset to its original value, every time, you need to tell your computer to do exactly that. It will also be simpler not to even use rep here, but copy its value to a different variable, and have the while loop use and decrement the other variable; so the same thing happens every time.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148