80.9k views
5 votes
Consider the following two code segments. Assume that the int variables m and n have been properly declared and initialized and are both greater than 0.

for (int i = 0; i < m * n; i++)
{
System.out.print("A");
}
for (int j = 1; j <= m; j++)
{
for (int k = 1; k < n; k++)
{
System.out.print("B");
}
}
Assume that the initial values of m and n are the same in code segment I as they are in code segment II. Which of the following correctly compares the number of times that "A" and "B" are printed when each code segment is executed?

User Kartheek
by
6.0k points

1 Answer

5 votes
The number of times that "A" is printed in code segment I is equal to m * n, while the number of times that "B" is printed in code segment II is equal to (m - 1) * n.

Therefore, the number of times that "A" is printed is equal to the number of times that "B" is printed if and only if m * n = (m - 1) * n, which simplifies to m = 1.

In other words, if m is equal to 1, then the two code segments will print the same number of "A"s and "B"s. If m is greater than 1, then code segment I will print more "A"s than code segment II will print "B"s. If m is less than 1, then code segment II will print more "B"s than code segment I will print "A"s.
User Aye
by
5.3k points