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;
}
}
CodePudding user response:
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.