Exercise 88
Exercise 88
In case 1:
- In sum1(5) n = 5, s =0
1. Check n> 0 5>0 -> T
s = 0 +1 =1
n = 5 – 1 =4
2. Check n> 0 4>0 -> T
s = 1 +1 = 2
n = 4 – 1 =3
3. Check n> 0 3>0 -> T
s = 2+1 =3
n = 3– 1 =2
4. Check n> 0 2>0 -> T
s = 3+1=4
n = 2-1 =1
5. Check n> 0 1>0 -> T
s = 4+1=5
n = 1-1 =0
6. Check n>0 0>0 -> F
End while
s=5
- In sum2(), val = 5 and s = 0:
1. Check val> 0 5>0 -> T
s = 0+1=1
val = 5-1 =4
2. Check val> 0 4>0 -> T
s = 1+1=2
val = 4-1 =3
3. Check val> 0 3>0 -> T
s = 2+1=3
val = 3-1 =2
4. Check val> 0 2>0 -> T
s = 3+1=4
val = 2-1 =1
5. Check val> 0 1>0 -> T
s = 4+1=5
val = 1-1 =0
6. Check val> 0 0>0 -> F
End while
s=5
- In sum3(), s=0 and val=0 (in sum2 the value of val fall down to 0), so the fomula is for i in range
(0,0,-1) , return s to 0
In case 2:
- In sum1(5) n = 5, s =0
1. Check n> 0 5>0 -> T
s = 0 +1 =1
n = 5 – 1 =4
2. Check n> 0 4>0 -> T
s = 1 +1 = 2
n = 4 – 1 =3
3. Check n> 0 3>0 -> T
s = 2+1 =3
n = 3– 1 =2
4. Check n> 0 2>0 -> T
s = 3+1=4
n = 2-1 =1
5. Check n> 0 1>0 -> T
s = 4+1=5
n = 1-1 =0
6. Check n>0 0>0 -> F
End while
s=5
- In sum3(), val = 5 and s = 0:
Exercise 89:
It will print an infinitie number of * until you manually stop the program. Because the loop condition is
a<1000, the variable a = 0 and is never updated inside the loop.
As a result the loop continuously remain true, the result is infinite loop
Exercise 90:
The loop a will begin from 0 and end at 99, with 100 times
The loop b will begin from 0 and end at 39, with 40 times
The condition to print * mark is (a+b)%2=0, it mean the sum is even number.
If a is even, b must be aslo be even => the range from 0 to 39 has 20 even number => 50*20=1000
If a is odd, b must be aslo be odd => the range from 0 to 39 has 20 odd number => 50*20 = 1000
Exercise 93: