Loops Q Suppose we make the following values in this order a
Loops
Q)
Suppose we make the following values in this order available to the algorithm on page 209: 5 -1 -3 7 3 -6 5 8 -8 2 -2 1 -9 -5 9 -2 0 6 -7 -6 4 2 -2 2 4
What value is in the variable sum when the algorithm ends?
Solution
What does this algorithm does?
It reads the 10 integer positive from user and sums up the numbers and ignores negative number.
So the input number are : 5 -1 -3 7 3 -6 5 8 -8 2 -2 1 -9 -5 9 -2 0 6 -7 -6 4 2 -2 2 4
5 is positive number so it adds up to sum and increment posCount to 1, sum is 5
-1 Is negative number so it ignores,
-3 Is negative number so it ignores,
7 is positive number so it adds up to sum and increment posCount to 2, sum is 12
3 is positive number so it adds up to sum and increment posCount to 3, sum is 15
-6 Is negative number so it ignores,
5 is positive number so it adds up to sum and increment posCount to 4, sum is 20
8 is positive number so it adds up to sum and increment posCount to 5, sum is 28
-8 Is negative number so it ignores,
2 is positive number so it adds up to sum and increment posCount to 6, sum is 30
-2 Is negative number so it ignores,
1 is positive number so it adds up to sum and increment posCount to 7, sum is 31
-9 Is negative number so it ignores,
-5 Is negative number so it ignores,
9 is positive number so it adds up to sum and increment posCount to 8, sum is 40
-2 Is negative number so it ignores,
0 Is negative number so it ignores,
6 is positive number so it adds up to sum and increment posCount to 9, sum is 46,
-7 Is negative number so it ignores,
-6 Is negative number so it ignores,
4 is positive number so it adds up to sum and increment posCount to 10, sum is 50,
posCount reaches 10 so loop exits..
sum is 50
