WEBVTT
00:00:00.380 --> 00:00:03.848
You've just worked with Sarah to write and understand several loops, and what
00:00:03.848 --> 00:00:08.326
will often happen to you that you have a loop that's really mysterious. And
00:00:08.326 --> 00:00:11.890
I'll give you an example. Here's some code that comes from a program that you
00:00:11.890 --> 00:00:15.920
will improve in a bit to solve a common problem, namely to identify reverse
00:00:15.920 --> 00:00:21.168
digits in a credit card. So let's see what this code does. What you always want
00:00:21.168 --> 00:00:24.860
to do is get out a sheet of paper. Here's my sheet of paper. You make a table.
00:00:24.860 --> 00:00:28.890
One column for every variable. There's a variable n, there's a variable sum.
00:00:28.890 --> 00:00:32.017
Now, it's always a good idea to take a marker, I like to use a paper clip to
00:00:32.017 --> 00:00:38.696
mark where we are. So, we set n to 365 and we set the sum to 0. Now, we enter
00:00:38.696 --> 00:00:43.216
the loop. Is n greater than 0? It sure is. We get to this statement. Now, we
00:00:43.216 --> 00:00:48.422
need to compute n modulo 10. That's the last digit of n. That would be 5. and
00:00:48.422 --> 00:00:53.556
now we have a new variable! We record it, we put in the 5. Moving on, sum is
00:00:53.556 --> 00:00:57.460
sum plus digit, n is n divided by 10, it's an integer division so we discard
00:00:57.460 --> 00:01:03.944
the remainder. We move to the top of the loop. Is n greater than 0? Compute n
00:01:03.944 --> 00:01:10.502
MOD 10, 36 MOD 10 is 6, store that in the digit. Sum is sum plus digit. It is
00:01:10.502 --> 00:01:14.960
11. n is n, what, 10. Now, n is 3. Back to the top of the loop. Is 3 greater
00:01:14.960 --> 00:01:20.288
than 0? It barely is, so we stay in the loop. Now, we need to take 3 MOD 10.
00:01:20.288 --> 00:01:24.444
That's 3. Add it to the sum. Divide n by 10, that's an integer division, so now
00:01:24.444 --> 00:01:28.950
we get 0. 0 is no longer greater than 0. We fall out of the loop, and go to
00:01:28.950 --> 00:01:33.650
this statement. And what are we printing? You're printing 14. Okay, well,
00:01:33.650 --> 00:01:38.124
what's 14? Well, we've computed all of the digits of the number 365, 3, the 6,
00:01:38.124 --> 00:01:45.295
the 5, and we've computed their sum. 14 is the sum of the digits. And that's
00:01:45.295 --> 00:01:49.320
almost what one needs to do in order to verify a credit card. You'll see in
00:01:49.320 --> 00:01:53.279
your next programming assignment what sum of digits you exactly need to do.