English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Assume that readInt reads and returns one integer value

int x, sumNeg=0, sumPos=0;
x=readInt();
while ( x != 0)
{
if (x<0)
sumNeg += x;
if (x>0)
sumPos +=x;
}

if (sumNeg < -8)
S.O.P.ln("negative sum: " + sumNeg);
if (sumPos > 8)
S.O.P.ln("positive sum: " + sumPos);

which of the following inputs would cause every line of code to be executed at least once?

0

2 4 6 8

2 -2 4 -4 0

4 -4 6 -6 0
-2 -4 -6- -8 0

2007-08-14 02:58:41 · 2 answers · asked by dingdong 1 in Computers & Internet Programming & Design

how did you get your sumPos and sumNeg answers

2007-08-14 03:33:31 · update #1

2 answers

The program usually won't terminate as written, because readInt() is called outside the while loop. Whatever value is read first, if non-zero, will cause the while loop to run infinitely.

If you instead mean:

==================
while ((x = readInt()) != 0) {
if (x < 0) sumNeg += x;
if (x > 0) sumPos += x;
}

if (sumNeg < -8) ...
if (sumPos > 8) ...
===================

That code totals up the positive numbers in sumPos, the negative numbers in sumNeg, and stops taking new numbers on zero.

If you want every line of code to execute, you have to be sure that:
(a) You enter at least one negative number (to test if x < 0)
(b) You enter at least one positive number (to test if x > 0)
(c) The sum of all negative numbers you enter is less than -8 (to test if sumNeg < -8)
(d) The sum of all positive numbers you enter is greater than 8 (to test if sumPos > 8)
(e) You enter zero last to terminate the while() loop

Of the data sets you list, only 4 -4 6 -6 0 satisfies all those conditions. sumPos would be 10 (from 4 + 6) and sumNeg would be -10 (from -4 + -6). As for the others:

0 wouldn't execute anything inside the while() loop at all.

2 4 6 8 wouldn't ever execute the "if x < 0" statement, and wouldn't terminate the while() loop, so nothing below it would execute.

2 -2 4 -4 0 would execute all the statements in the while loop, and terminate the while loop, but would not execute either of the printlns at the bottom of the method, since sumPos would be 6 (from 2 + 4) and sumNeg -6 (from -2 + -4), at the end.

-2 -4 -6 -8 0 would not execute the "if x > 0" statement, or "if sumPos > 8" statement.

2007-08-14 03:46:08 · answer #1 · answered by McFate 7 · 1 0

4 -4 6 -6 0

sumpos = 10
sumneg = -10

therefore every line will fire
what help do you need? or were you just testing me?

2007-08-14 10:13:06 · answer #2 · answered by Surger1 3 · 0 0

fedest.com, questions and answers