Hello!
I’ve got a question about for loops specifically regarding initializing variables in different places and causing different results, even though I expected the same:
Using this nested for loop, I’ve initialized both integers in the first for loop:
for(int32 Index = 0, Comparison = Index +1; Index < Word.Len(); ++Index)
{
for (;Comparison < Word.Len(); Comparison ++)
{
if (Word[Index] == Word[Comparison])
{
return false;
}
}
}
The loop doesn’t find any repeating letters other than the first character in the array, shown here:
However, using THIS nested for loop, with the integers initialized within different for loops in this way:
for (int32 Index = 0; Index < Word.Len() -1; ++Index)
{
for (int32 Comparison = Index +1; Comparison < Word.Len(); Comparison++)
{
if (Word[Index] == Word[Comparison])
{
return false;
}
}
}
Allows the code to run as intended:
My question is why does this happen? Shouldn’t initializing the variables wherever they may be still have the same result? I wonder if this has something to do with scope, which is a question I asked on the forums last week, and I’m concerned that maybe I haven’t fully grasped the idea of scope yet.
Thanks in advance for your replies!