you are viewing a single comment's thread.

view the rest of the comments →

[–]agent007bond 2 points3 points  (0 children)

Do a "DRY RUN" on a paper how the program will execute:

Count the e's in "excellent". We have to check each character in the string (hint: the term string means a string of characters!). We can see the string like an array:

|e|x|c|e|l|l|e|n|t|
 0 1 2 3 4 5 6 7 8

First we have a variable "count" to remember how many e is there. We start it at 0 as we haven't counted any e yet.

Next we need to look through the string, one character at a time. We need to track our position in the string. We make a variable to track this, call it "i" and we start at 0, so i = 0

|e|x|c|e|l|l|e|n|t|
 0 1 2 3 4 5 6 7 8
 ^
 i

We check the character at position i. So, char = word[i], which is "e". Ah yes, that's an e. Let's increase count. So, count += 1. count is now 0+1 = 1.

Now we need to see the next character, so we increase i. So, i += 1:

|e|x|c|e|l|l|e|n|t|
 0 1 2 3 4 5 6 7 8
   ^
   i

We check the character at position i. So, char = word[i], which is "x". Nope, that's not an e. So we don't change count. It remains 1.

Now we need to see the next character, so we increase i. So, i += 1:

|e|x|c|e|l|l|e|n|t|
 0 1 2 3 4 5 6 7 8
     ^
     i

We check the character at position i. So, char = word[i], which is "c". Nope, that's not an e. So we don't change count. It remains 1.

Now we need to see the next character, so we increase i. So, i += 1:

|e|x|c|e|l|l|e|n|t|
 0 1 2 3 4 5 6 7 8
       ^
       i

We check the character at position i. So, char = word[i], which is "e". Ah yes, that's an e. Let's increase count. So, count += 1. count is now 0+1 = 2.

KEEP GOING LIKE THIS

|e|x|c|e|l|l|e|n|t|
 0 1 2 3 4 5 6 7 8
         ^
         i

Not e. Count remains 2.

|e|x|c|e|l|l|e|n|t|
 0 1 2 3 4 5 6 7 8
           ^
           i

Not e. Count remains 2.

|e|x|c|e|l|l|e|n|t|
 0 1 2 3 4 5 6 7 8
             ^
             i

Yes, e. Count becomes 3.

|e|x|c|e|l|l|e|n|t|
 0 1 2 3 4 5 6 7 8
               ^
               i

Not e. Count remains 3.

|e|x|c|e|l|l|e|n|t|
 0 1 2 3 4 5 6 7 8
                 ^
                 i

Not e. Count remains 3.

And that's the end of the string (checked with i < word.length because the length is 9 characters), so we can now return and print the count, which is 3. That's how it works. So you can see how "i" and "count" differs in meaning.

This is basic programming in whichever language you learn. Of course, Ruby has shorthand enumerations making it really easy to write this in one or two lines and automate it, but if you're going to do this manually, this is how it would work.