Since
count
is found in the main function, you can't use it here. However,
count
was passed into the
rectangle
function through the variable
y
, so you can use that variable here.
The loop you wrote in lines 6 and 7 are an infinite loop--it will never end. Nothing is changing the value
number
or the value
count
, so
number
will always be
<= count
. Line 7 will execute over and over and over without ending.
There are a number of ways to provide the loop. Using the while loop, you can do:
1 2 3 4 5 6 7 8 9
|
void rectangle (char ch, int x, int y)
{
int number = 1;
while(number <= y) // correct variable here
{ // Curly braces allow multiple statements in while loop
line(ch,x);
number++; // Increment the counter
}
}
|
In your original post, lines 11 and 12 are a 'for' loop. You could use the same type of loop here.
1 2 3 4 5 6 7
|
void rectangle (char ch, int x, int y)
{
for (int i = 0; i < y; i++)
{
line(ch,x);
}
}
|
A few style things to note:
(1) Typical C and C++ usage is to start loops at 0 and end when they reach the threshold (
for (int i = 0; i < y; i++)
) rather than looping from 1 through the threshold (
for (int i = 1; i <= y; i++)
. This will come in especially handy when you learn more about indexing into arrays. You should probably get into the habit of this now (see lines 11 and 12 of original post).
(2) In C++ you can declare a variable inside a 'for' statement that is scoped exclusively to the for loop. This allows you to do
for (int i = 0; i < y; i++)
rather than
int i; for (i = 0; i < y; i++)
. If the counter is not needed after the loop exits, you can declare the counter when you need it.
(3) It is usually a good idea to add curly braces around the content of an if/for/while/etc. block, even if it is only a single statement. As you write more advanced code, you will get to points where you want to add or remove statements from an if/for/while/etc., and remembering to add or remove curly braces can become a hassle. Plus the curlys can be used to better visually show program structure.