Return to Video

Hand Tracing - Intro to Java Programming

  • 0:00 - 0:04
    You've just worked with Sarah to write and understand several loops, and what
  • 0:04 - 0:08
    will often happen to you that you have a loop that's really mysterious. And
  • 0:08 - 0:12
    I'll give you an example. Here's some code that comes from a program that you
  • 0:12 - 0:16
    will improve in a bit to solve a common problem, namely to identify reverse
  • 0:16 - 0:21
    digits in a credit card. So let's see what this code does. What you always want
  • 0:21 - 0:25
    to do is get out a sheet of paper. Here's my sheet of paper. You make a table.
  • 0:25 - 0:30
    One column for every variable. There's a variable n, there's a variable sum.
  • 0:30 - 0:34
    Now, it's always a good idea to take a marker, I like to use a paper clip, to
  • 0:34 - 0:39
    mark where we are. So, we set n to 365 and we set the sum to 0. Now we enter
  • 0:39 - 0:44
    the loop. Is n greater than 0? It sure is. We get to this statement. Now we
  • 0:44 - 0:49
    need to compute n modulo 10. That's the last digit of n. That would be 5. and
  • 0:49 - 0:54
    now we have a new variable! We record it, we put in the 5. Moving on, sum is
  • 0:54 - 0:59
    sum plus digit, n is n divided by 10, it's an integer division, so we discard
  • 0:59 - 1:05
    the remainder. We move to the top of the loop. Is n greater than zero? Compute
  • 1:05 - 1:10
    n MOD 10, 36 MOD 10 is 6, store that in the digit. Sum is sum plus digit. It is
  • 1:10 - 1:15
    11. N is n what 10, now n is 3. Back to the top of the loop. Is 3 greater than
  • 1:15 - 1:19
    zero? It barely is, so we stay in the loop. Now we need to take 3
  • 1:19 - 1:20
    [INAUDIBLE]
  • 1:20 - 1:25
    10. That's 3. Add it to the sum. Divide n by 10, that's an integer division, so
  • 1:25 - 1:29
    now we get 0. Zero is no longer greater than zero. We fall out of the loop, and
  • 1:29 - 1:34
    go to this statement. And what are we printing? You're priting 14. Okay, well
  • 1:34 - 1:39
    what's 14? Well, we've computed all of the digits of the number 365. 3, the 6,
  • 1:39 - 1:44
    the 5, and we've computed their sum. 14 is the sum of the digits. And that's
  • 1:44 - 1:48
    almost what one needs to do in order to verify a credit card. You'll see in
  • 1:48 - 1:53
    your next programming assignment what sum of digits you exactly need to do.
Title:
Hand Tracing - Intro to Java Programming
Description:

more » « less
Video Language:
English
Team:
Udacity
Project:
cs046: Intro to Programming
Duration:
01:54
Udacity Robot edited English subtitles for 11-11 Hand Tracing
Udacity Robot edited English subtitles for 11-11 Hand Tracing
Udacity Robot edited English subtitles for 11-11 Hand Tracing
Cogi-Admin edited English subtitles for 11-11 Hand Tracing
Cogi-Admin added a translation

English subtitles

Revisions Compare revisions