The new forums will be named Coin Return (based on the most recent vote)! You can check on the status and timeline of the transition to the new forums here.
The Guiding Principles and New Rules document is now in effect.
Okay, I'm studying for my intro to computer programming final, and I've got the following study question:
In the following pseudocode, how many times is "Hello" printed?
p = 2
q = 4
while p < q
print "Hello"
r = 1
while r < q
print "Hello"
r = r + 1
endwhile
p = p + 1
endwhile
Answers:
A. zero
B. four
C. six
D. eight
No matter how I look at it, I keep getting the answer to be D, but the answer key says that it should be C? Is that a mistake? And if it's not, could someone please explain it to me? By my reasoning, p is gonna be less than q twice, which means Hello gets printed twice. It also means that the inner loop gets executed twice, and each time r is less than q 3 times. 2 + 3 + 3 = 8.
Having run it myself, the answer is eight times. A simple Perl implementation:
#!/usr/bin/perl
use strict;
my $p = 2;
my $q = 4;
while ($p < $q)
{
print "Hello\n";
my $r = 1;
while ($r < $q)
{
print "Hello\n";
$r++;
}
$p++;
}
Your reasoning is correct: the inner loop over r is run 3 times, while the outer loop is run twice, thus giving you two "Hello"s for the outer loop, plus two times the three for the inner. Unless there's something else we're missing from the question, I can't see how it would give only six.
Other people have already answered this, but I thought I'd mention you can use code /code tags on this forum to preserve formatting. It helps a lot when you have programming questions.
Posts
Your reasoning is correct: the inner loop over r is run 3 times, while the outer loop is run twice, thus giving you two "Hello"s for the outer loop, plus two times the three for the inner. Unless there's something else we're missing from the question, I can't see how it would give only six.
http://www.audioentropy.com/