(upbeat music)
- [Narrator] I hope you've enjoyed your challenge,
here's a few possible solutions.
This is 02 solution from chapter two of the exercise files,
and here I've included several possible solutions
to our challenge.
The first one uses a for loop.
And you notice that I initialize count to zero
at the beginning of the for loop.
I test for the last element of string,
when it hits zero, this loop will no longer be true.
And I increment that count variable.
The body of the for loop is empty,
so I just have the semi colon.
This is called a body-less for loop.
And there's out print f that prints the result.
The second solution uses a while loop.
I initialize the count to zero,
and then a standard while loop that tests
for the end of the string.
Again, indexing the string with count,
and when the count hits the null terminator
the condition will no longer be true,
the loop will end, and the count is incremented
inside the body of the loop
and we print out the number of characters.
And then finally, using a range based for loop,
again I initialize count to zero.
I have the range based loop, where I have the variable X,
which will get each element of the string,
and I test to see when X is zero,
and when it's zero I break.
And I increment the count variable
and print the number of characters.
So I'll go ahead and build this and run it
and you'll see our result each time is the number 33,
which is indeed the number of characters in the string.
Counting the elements in the container is a common problem
with a number of possible solutions.
Different solution will lend themselves
to different types of problems
and different types of containers,
so it's a good idea to experiment with various approaches.