# Table-5 Counting

## Counting

• So far, we print all matching rows
• What are some problems with this approach?
• More useful to count the number of matching rows
• Make a "report"
• Requires some new variable manipulation code

So far we've used an if/print structure inside a loop to select certain rows to print or not. In this short section, we'll use a variable with a little code to count how many rows pass our if-filter.

## Code To Count

Count by making 3 additions to the standard loop/if/print structure we've used up to now:

• Three things to do counting:
• 1. Create a count variable and set it to 0 before the loop
`count = 0;`
• 2. Inside the if-statement, increase count by 1
`count = count + 1;`
-Above line increases the value in count by 1
-Evaluates the right hand side, then stores into variable (=)
• 3. Print the final value stored in count after the loop
`print("count:", count);`
• Pattern three parts, the same every time (create variable, increase count, print)
• This pattern of `x = x + 1;` increases the variable by 1 - you choose the x
• Works because the variable is just a label for a piece of information (not like a math variable)
• Challenge: how could we increment the count by 2?

Inside the if-statement, `count = count + 1;` increases whatever number is stored in count by 1 when the if-filter is true. This is a weird use of the equal sign (=) vs. how it works it mathematics. First the line evaluates the right hand side. Then it assigns that value back into the count variable, so in effect it increases the number stored in count by 1.

table5-1

Experiments:

• 1. Try commenting out or removing the print(row); line inside the { .. } then-code. What is the output now?
• 2. How many names start with "X"? Then change to count starting with "Y"?
• 3. How many girl names begin with "A"? Then change to count how many boy names begin with "A"?
• 4: What would happen if we moved count = 0 to inside the if-statement?
• 5: What if we moved the print just below the count = count + 1; line?

Experiment solutions:

> exercises