# Table Counting

• Thus far... print all matching rows
• Count the number of matching rows, make a "report"
• Requires some new variable manipulation code

Thus 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 times an if-test is true. Below is a loop as we have seen before that detects all the names that start with "A". After printing the rows, the code prints a summary of how many names started with "A".

## Code To Count

Three 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 increases the value in count by 1 (if if-test is true)
--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 (init, increment, print)
• Just know that `x = x + 1;` increments the value stored in a variable

Inside the if-statement, `count = count + 1;` increases whatever number is stored in count by 1 when the if-test is true. This is a weird use of the equal sign = vs. how it works it mathematics. First it 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. The increase-by-1 operation is so common in computer code, many languages including Javascript support the shortcut `count++;` to mean increase by 1.

 table = new SimpleTable("baby-2010.csv"); count = 0; for (row: table) { if (row.getField("name").startsWith("A")) { print(row); count = count + 1; // increases the value in count by 1 } } print("count:", count);

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"?

Experiment solutions:

> exercises