Help Me Understand this FOR loop!

So in theory this for loop is suppose get the words first letter and check if it matches any other letters in the same word. If there are no matching letters then the word is classed as an Isogram.

I’m confused how the the results of this for loop is 1,2,3,4 exactly.

So when the first loop runs, Index is 0 then 1 is added to index making it 1. After this point I get lost and don’t understand. Does Comparison++ even do anything in the first loop because its a post-increment? and how does it effect the code when runs in the 2nd and the other loops.

If someone could break it down for me and explain I would really appreciate it!

First, you did declare the default value for Comparison which is Comparison = Index + 1;. The index is 0 so this results in Comparison to be 1. Then you did write Comparison++ which adds 1 after every loop.

In your code, the first loop is going to be the default value 1 and then it just adds 1 after every loop so it ends up being 1,2,3,4. I hope this helps.

1 Like

I would probably change that for loop as Index doesn’t need to be in there. You can do that before it with bIsogram. There’s also no point in doing = Index + 1 when Index is always 0.

I’m sure these things are confusing you.

A typical for loop is

for (int i = 0; i < n; i++) {}

In this example, i starts at 0 and increments by 1 each time the for loop runs as long as each new loop through it is less than n. i doesn’t go to 0 each time and the first run is 0.

https://www.w3schools.com/cpp/cpp_for_loop.asp

To add, I think if you’re going according to the course that they fix these problems if you continue.

2 Likes

The for loop has three parts

  1. the instantiation which runs before the loop code, this only runs once
  2. the comparison which determines if the loop should break or stop, this runs before each loop
  3. the incrementor which changes some variable to adjust the looping code, this runs after the code block

for (instantiation; comparison; incrementor) { ... }

Another way of writing a for loop is:

int32 Index = 0;
int32 Comparison = Index+1;
while(Comparison < Word.Len()) {
  ...
  Comparison++;
}

Your code prints 1234 because you only increment the Comparison variable. Then Comparison equals your word length and the loop breaks.

BUILD BUILD BUILD BUILD
^^    ^ ^   ^  ^  ^   ^
01      2      3      4

To complete your task you would have to have nested for loops.
The outer loop increments the Index and the inner loop increments the Comparison.

for(Index=0;Index<Word.Len()-1;Index++){
  for(Comparison=Index+1;Comparison<Word.Len();Comparison++){
    ...
  }
}
2 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.