Rewriting a FOR loop into a WHILE loop

Mar 13, 2013 at 5:12am
I've been trying to rewrite this For loop for making an Asterisk square/rectangle:

#include <iostream>
using namespace std;
int main () {
cout << "Enter the height: ";
int x,y,a,b;
cin >> x;
cout << "Enter the width: ";
cin >> y;
for (a=1; a<=x; a++) {
for (b=1; b<=y; b++)
cout << '*';
cout << endl;
}
cout << endl;
system ("pause");
}



into a While Loop which I can't seem to figure out how to properly do.
What I have so far is:

#include <iostream>
using namespace std;
int main () {
cout << "Enter the height: ";
int x,y;
cin >> x;
cout << "Enter the width: ";
cin >> y;
int a = 1, b = 1;
while (x>=a) {
while (y>b) {cout << '*'; b++;}
cout << '*'; a++; cout << endl;}


cout << endl;
system ("pause");
}


which, using an example like a 5x5 sqaure, it comes out as:
*****
*
*
*
*

instead of

*****
*****
*****
*****
*****
which appears in the FOR loop.


And I have no idea why the WHILE loop appears that way.
Last edited on Mar 13, 2013 at 5:13am
Mar 13, 2013 at 5:16am
Your inner while loop doesn't have the same condition as the inner for loop. Also, your outer while loop has an additional * that is being printed. The value of b is also not being reset every iteration of the outer while loop, unlike the for loop example. Do that and I think it'll work.
Topic archived. No new replies allowed.