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?
public class Program {
public static int CountDs(string str)
{ //Keeping count of the answer with ans
int ans = 0;
//Creating a for-loop to iterate over the string
for(int i = 0; i < str.Length; i++)
{
//If at the str at index i either equals d or D, increment ans by 1
if(str[i] == 'd' || str[i] == 'D')
{
ans++;
}
}
return ans;
}
}
public class Program {
public static int CountDs(string str)
{ //Keeping count of the answer with ans
int ans = 0;
//Creating a for-loop to iterate over the string
for(int i = 0; i < str.Length; i++)
{
//If at the str at index i either equals d or D, increment ans by 1
if(str[i] == 'd' || str[i] == 'D')
{
ans++;
}
}
return ans;
}
}
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
Doombox
Doombox2w ago
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 look
PocketPixie
PocketPixie2w ago
Thank you for the answer, Task. It does make sense once the
d
d
or
D
D
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.
Doombox
Doombox2w ago
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
Want results from more Discord servers?
Add your server