Where is the letter of the array saved?
Hello everyone,
Just a quick question. I understand this code based upon the comments but I am wondering why ans just being incremented has anything to do with the logic in comparing where index i is in the string?
How does the program know how many D's are in the string if it just increments after coming across a D or a d? Where does it 'keep' the d or D?
3 Replies
imagine you are reading a page in a book, you have a scrap piece of paper and a pen, you scan the page letter by letter, each time you see a
d
you make a little mark on the bit of scrap paper, at the end you have a count of the occurrences of the letter d
but no record of where they are or on what context they were used, just that you saw them
that's functionally how that bit of code works
the for loop and str[i]
are purely the act of scanning the page, they are just the mechanism by which you lookThank you for the answer, Task. It does make sense once the or is counted for after iterating through the string. So the ans is acting as a counting mechanism for how many times the above shows up.
precisely, this is pretty much the most basic way to search for anything in any language, good old linear search, what you do when you find a result is sort of irrelevant
in this case you're just counting each time you find a match, equally you could just store the index of the first ocurrence and
break;
out of the loop