Trouble understanding the nested for loop in Lecture 32

Hi,

I followed the course and was able to understand everything until here perfectly.
My first trouble began with the challenge for finishing the if loop. Also nested loops have not been discussed beforehand and the teacher was a little to quick in assuming everything is clear.

Now I got it all working, but I don’t quite understand the nested for loop in “english words”

int32 HiddenWordLength = MyHiddenWord.length();
for (int32 MyHiddenWordChar = 0; MyHiddenWordChar < HiddenWordLength; MyHiddenWordChar++) {
for (int32 GuessChar = 0; GuessChar < HiddenWordLength; GuessChar++) {
//compare letters against the hidden word

  	if (Guess[GuessChar] == MyHiddenWord[MyHiddenWordChar]) //if they match then
  	{
  		if (MyHiddenWordChar == GuessChar) //if they are in the same place
  		{
  			BullCowCount.Bulls++;
  		}
  		else //if they are not in the same place
  		{
  			BullCowCount.Cows++;
  		}
  	}
  		// if they are in the same place
  			//incriment bulls
  		//if they are not (else)
  			//incriment cows 
  }

}

From what I understand from nested for loops before is, that the outer loop only proceeds once the inner loop is completely finished (or interrupted).

Let’s say the hidden word indeed is “ant” and my guess is “and”

  • So the first check would be my guessed “a” getting compared to the hidden “a”. True, Bulls++.

What then?

  • It increments GuessChar by one, and basically compares my guessed “n” to the hidden “a”? False, no else defined

  • Increment again, check guessed “d” to compare with hidden “a”, False, no else defined.

Now MyHiddenWordChar increments by 1 and it starts again with comparing my guessed “a” to the hidden “n”.

And so forth?

Just trying to understand, that is what’s going on here, before I continue. And I am pretty sure there will be some improvements in further lessons.

Thanks!

Chris

Yes, it also helps to write it down to illustrate it. Using your example of HW = “ant” and Guess = “and”

HWChar = 0, GChar = 0,
a nt == a nd;
HWChar = 0, GChar = 1,
a nt == a n d
HWChar = 0, GChar = 2,
a nt == an d

HWChar = 1, GChar = 0,
a n t == a nd

etc.

1 Like

Okay thank you. I noticed while writing the post, that I seemed to understand it. Writing it down apparently helps, as you stated.

Thanks!

The syntax was pretty easy to this point, though coming up with the concept was the harder part. But I guess that is a big part of programming anyway. It might have helped to know what exactly that game is in terms of when to add bulls and when cows (I know now) in order to pseudo code it without help.

Anyways, I can continue now.

Privacy & Terms