Loop Design: Counting & Subsequent Code Duplication <p>Exercise 3-3 in Accelerated C++ has led me to two broader questions about loop design. The exercise's challenge is to read an arbitrary number of words into a vector, then output the number of times a given word appears in that input. I've included my relevant code below:</p> <pre><code>string currentWord = words[0]; words_sz currentWordCount = 1; // invariant: we have counted i of the current words in the vector for (words_sz i = 1; i &lt; size; ++i) { if (currentWord != words[i]) { cout &lt;&lt; currentWord &lt;&lt; ": " &lt;&lt; currentWordCount &lt;&lt; endl; currentWord = words[i]; currentWordCount = 0; } ++currentWordCount; } cout &lt;&lt; currentWord &lt;&lt; ": " &lt;&lt; currentWordCount &lt;&lt; endl; </code></pre> <p>Note that the output code has to occur again outside the loop to deal with the last word. I realize I could move it to a function and simply call <em>the function</em> twice if I was worried about the complexity of duplicated code.</p> <p><strong>Question 1:</strong> Is this sort of workaround is common? Is there a typical way to refactor the loop to avoid such duplication?</p> <p><strong>Question 2:</strong> While my solution is straightforward, I'm used to counting from zero. Is there a more-acceptable way to write the loop respecting that? Or is this the optimal implementation?</p>