|
From: Schedler, K. <Kur...@hi...> - 2001-07-20 18:16:35
|
I'll just give you a hint this time instead of writing the code for you. If
you want to reverse the pattern,
try counting 1, 2, 3, ... 9 instead of 9, 8, 7, ... 1. I'll also tell you
that I only had to change three lines
in my original code to make it print out the pattern in reverse, and those
changes were very insignificant.
You keep hitting infinite loops because you put a condition in the while
clause (stars < 10), but you never
change the value you're testing within the loop, so the condition will never
become false. Notice my
original while loop:
while (stars > 0)
{
putchar('*');
stars--;
}
stars starts out at some value greater than zero (since we're setting it
equal to lines) and each time
through the loop, it decreases by one (stars--, the minus-minus is the
decrement operator). Without
decrementing stars, it stays the same greater-than-zero value and the while
condition will be true
forever. Let's look at your code:
lines = 9;
stars = 1;
while (lines > 0)
{
putchar('*');
stars++;
while (stars < 10)
{
putchar('\n');
lines--;
}
}
The first time we go through the loop, lines = 9 and stars = 1. We output
one asterisk and increment
stars to 2. We enter the nested loop and 2 is less than 10 so we output a
newline character and
decrement lines to 8. Then since stars is still equal to 2, we do the loop
again. Another
newline is output and lines is decremented to 7. On and on we go,
outputting newlines and
decrementing lines by one.
And as Ioannos said, you can use cout << '*' instead of putchar('*').
-----Original Message-----
From: Tre...@ao... [mailto:Tre...@ao...]
Sent: Friday, July 20, 2001 10:46 AM
To: dev...@li...
Subject: Re: [Dev-C++] nested loop
Thank you for your help :) I am now trying to reverse the pattern and I am
getting an infinite loop.....can you see what is wrong.....it looks fine to
me.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int pattern = 0;
int lines = 0;
int stars;
cout << "Enter 1 for pattern1 or 2 for pattern2: " << endl;
cin >> pattern;
if (pattern == 1)
{
lines = 9;
while (lines > 0)
{
stars = lines;
while (stars > 0)
{
putchar('*');
stars--;
}
putchar('\n');
lines--;
}
}
else if (pattern == 2)
{
lines = 9;
stars = 1;
while (lines > 0)
{
putchar('*');
stars++;
while (stars < 10)
{
putchar('\n');
lines--;
}
}
} //end if
return 0;
}
"The sender believes that this E-mail and any attachments were free of any
virus, worm, Trojan horse, and/or malicious code when sent. This message
and its attachments could have been infected during transmission. By
reading the message and opening any attachments, the recipient accepts full
responsibility for taking protective and remedial action about viruses and
other defects. The sender's employer is not liable for any loss or damage
arising in any way from this message or its attachments."
|