Concepts / Conditional Statements and Boolean Logic

Conditional Statements and Boolean Logic

The counter pattern is a fundamental computational technique: initialize a counter to 0, loop through data, check a condition, and increment the counter when the condition is true.

  • Programming

A Selective Accumulator

Many programming tasks require counting how often something happens. The counter pattern provides a reliable way to do this: start a counter at 0, examine each item in some data, test a condition, and increase the counter only when that condition is true. The counter therefore records only the events that matter.

Character counting is a straightforward application of this pattern. To count a target character in a string, a loop examines each character and a conditional statement checks whether that character matches the target. A true comparison causes the counter to increase; a false comparison leaves it unchanged.

count = 0initial valueExamine itemnext characterConditiondoes it match?count + 1match foundcountno matchFinal countafter all itemsbegin looptest itemtruefalsecontinuecontinueno items remain
What happens as a program counts matching items?

Counting Matches in banana

Worked example

Counting the letter a

Count how many times the letter a appears in the word banana.

  1. 1
    Initialize

    Begin with count set to 0 because no characters have been examined yet.

  2. 2
    Examine each character

    Move through banana one character at a time using a loop.

  3. 3
    Check the condition

    For each character, test whether the character is equal to a.

  4. 4
    Increment selectively

    Increase count only for the matching characters. The matches occur at the second, fourth, and sixth characters.

  5. 5
    Finish

    After every character has been examined, the accumulated count is 3.

Result

The letter a appears 3 times in banana.

bno matchamatch: +1nno matchamatch: +1nno matchamatch: +13total matchescontributes 1contributes 1contributes 1
Which character positions match the target character, and how do those matches contribute to the total?

What do you think happens?

Before reading the trace, predict the counter value after each character in banana is examined while counting a.

  • 0, 1, 1, 2, 2, 3

  • 1, 1, 2, 2, 3, 3

  • 0, 0, 0, 1, 1, 1

Reveal answer
Answer:

0, 1, 1, 2, 2, 3

The counter begins at 0. It increases only at the second, fourth, and sixth characters, where the examined character is a.

Tracing the Counter State

A counter trace makes the pattern visible. For banana, the counter starts at 0. The first character does not match a, so the value remains 0. The second character matches, so the value becomes 1. The third character leaves it at 1. The fourth match changes it to 2. The fifth character leaves it at 2, and the final match changes it to 3.

0before loop0after b1after a1after n2after a2after n3after ab does not matcha matchesn does not matcha matchesn does not matcha matches
How does the counter change after each character is examined?

The important behavior is selective change. A false condition does not reset the counter and does not decrease it; the counter simply remains at its current value. A true condition increases the value by exactly 1. Repeating these two possibilities lets the counter accumulate the total number of matches.

letter == acomparison resultTruematchFalseno matchcount + 1counter changescountcounter stays the sametruefalseincrementno increment
How does the Boolean result of the character comparison determine whether the counter changes?

Reusable Character Counting

Once the loop and counter logic is understood, it can be encapsulated in a reusable function. The function named count accepts two arguments: the string to search and the letter to count. It performs the same initialization, iteration, comparison, and selective incrementing for whatever inputs are supplied.

Input stringtext to searchTarget charactercharacter to countcountreusable logicCharacter countreturned resultargumentargumentreturns
How do the input string and target character enter a reusable function, and how does the function return the count?
Best practice

When the same counting task may be needed for different strings or different characters, place the counter pattern in a function instead of rewriting the loop each time. Parameters make the logic flexible, reusable, and easier to maintain.

Mistakes That Break the Pattern

  • Common mistake

    Initializing the counter inside the loop

    What it looks like

    The counter is reset to 0 each time another character is examined.

    Why it fails

    Earlier matches are erased, so the counter cannot accumulate the total.

    Do this instead

    Initialize the counter before the loop begins.

  • Common mistake

    Forgetting to increment the counter

    What it looks like

    The condition identifies a matching character, but no increment occurs.

    Why it fails

    The program detects matches but never records them in the total.

    Do this instead

    Increment the counter when the condition is true.

  • Common mistake

    Using assignment instead of comparison

    What it looks like
    Using = where the condition needs ==.
    Why it fails

    Assignment and comparison serve different purposes; the condition must compare the current character with the target character.

    Do this instead
    Use == for the character comparison described by the counter pattern.
  • Common mistake

    Placing the increment outside the conditional block

    What it looks like

    The counter increases after every character, whether or not the character matches.

    Why it fails

    Non-matching characters are incorrectly included in the total.

    Do this instead

    Place the increment so that it occurs only when the condition is true.

Practice the Trace

EASY

Trace the counter pattern for the word banana when the target character is n. Write the counter value after each character is examined, then identify the final count.

Hints
  • Start the counter at 0.
  • Increase it only when the examined character matches n.
  • The counter remains unchanged for every other character.
MEDIUM

Design a reusable count function that accepts a string and a target character. Describe the two parameters, the condition tested inside the loop, and the value returned after the loop finishes.

Hints
  • Use one parameter for the string to search.
  • Use one parameter for the character to count.
  • Return the accumulated counter after every character has been examined.

Key Takeaways

  1. 1
    The counter pattern initializes a counter at 0, examines data in a loop, tests a condition, and increments only when the condition is true.
  2. 2
    Character counting uses a loop to visit each character and a conditional comparison to identify matches.
  3. 3
    A false condition leaves the counter unchanged, while a true condition increases it by 1.
  4. 4
    The character-counting pattern can be generalized into a reusable count function with a string parameter and a target-character parameter.
  5. 5
    The same pattern can support other tasks involving counted occurrences, tracked events, summed values, or condition-based accumulation.

At a glance

  • The counter pattern combines initialization, iteration, conditional testing, and selective incrementing.
  • Counting the letter a in banana produces 3 because the second, fourth, and sixth characters match.
  • Tracing the counter shows exactly when its state changes and when it remains unchanged.
  • A reusable function can accept the string and target character as parameters and return the accumulated count.

Related concepts

More concepts starting with C