Assignment 3, Question 2: Instructor's solution
Tracing function code:
10 int f(int x)
11 {
12 int sum=0;
13 while (x>0)
14 {
15 sum+=(x%10);
16 x/=10;
17 }
18 return(sum);
19 }
I work out the sample value x=567 (chosen at random).
Line # | x | sum | Condition
-----------------------------------
10 | 567 | ? |
-----------------------------------
12 | 567 | 0 |
-----------------------------------
13 | 567 | 0 | T
-----------------------------------
15 | 567 | 7 |
-----------------------------------
16 | 56 | 7 |
-----------------------------------
13 | 56 | 7 | T
-----------------------------------
15 | 56 |7+6=13|
-----------------------------------
16 | 5 | 13 |
-----------------------------------
13 | 5 | 13 | T
-----------------------------------
15 | 5 |13+5=18|
-----------------------------------
16 | 0 | 18 |
-----------------------------------
13 | 0 | 18 | F, exit loop
-----------------------------------
18 | return 18 to caller
-----------------------------------
Analysing how the sum accumulates (18=7+6+5 in this example),
one can conclude that function f calculates the sum of
digits in x.