(using only while loops) i want to write a program to produce a hollow rectangle,i.e if the user types 5 and 4, the result would be
*****
* *
* *
*****
Printable View
(using only while loops) i want to write a program to produce a hollow rectangle,i.e if the user types 5 and 4, the result would be
*****
* *
* *
*****
How far have you gotten? Show your code.
Code:#include <iostream.h>
void main()
{
int counter1=1, counter2;
int num1;
int num2;
cout<<"Number 1:";
cin>>num1;
cout<<"Number 2:";
cin>>num2;
counter1=num1;
counter2=num2;
while (counter1<=num1)
{
cout<<"*";
counter1++;
counter2=1;
while (counter2<=num2)
{
cout<<"*";
cout<<endl;
counter2++;
}
}
}
Please use the [code] tags when posting source code.
Hum, your program doesn't really display the right rectangle. First try to write a program that displays a filled rectangle, this is easier. Now for the hollow rectangle, you have to do something different depending on whether you are on the first (or last) line, or somewhere in the middle. The first and the last line are printed in full, but in the middle you only show the left-most and the right-most star.
So there are basically two ways you can go from here:
1) Use two different kind of loops (at the highest level). A) One kind to draw a filled horizontal line and B) one to draw a star at the start, then spaces and then another star. Then the whole program would just become a sequence of A) B) A)
2) Place a condition inside the second loop that checks whether you are inside the rectangle or on the outline. If you are inside, print a space, otherwise print a star. This doesn't change the loops, but requires an if condition.
just to add, if you can only use while loops (this looks like a school project) you can use whiles to simulate if's:
Code:
CONDITION1 = /*some setting condition routine*/;
IfSim = false
while (CONDITION1 == true && IfSim == false)
{
stuff
IfSim = true;
}
while (CONDITION1 == false && IfSim == false)
{
stuff
IfSim = true;
}