Table Counting

< Code In The Browser

Thus far we've used an if/print structure inside a loop to select certain rows to print or not. Now 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".

The count version of the code has three additions to the previous printing version of the code:

  1. count = 0; -- Before the loop, create a count variable and set it to 0.
  2. count = count + 1 -- In the loop, this increases whatever number is stored in count by 1 when the if statement 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. Placing a ++ after a variable is a shorthand for this.
  3. print("count:", count); -- finally, outside the loop we need some code to print the value stored in the count variable.

Counting Multiple Things

Do more boy or girl names begin with A? We want a program which by the end prints "girl count:nn" and "boy count:nn", counting whatever characteristic we are looking for. One approach is to copy/paste the loop, with the first loop counting for girls, and then the second loop counting for boys. This approach works, although it's a little wordy.

Another approach is to use two counters, one for the girl case and one for the boy case: countG and countB. Initialize both counters to 0 outside the loop. Then in the loop, have two if statments, one to manage each counter. When the loop is done, just print both counters. (solution below)


Class Survey


As another example of a table, we have the class survey data with people's favorite movies and what have you. The questions for this survey were:

The survey answers are automatically translated to a google spreadsheet which can be exported in csv table. This data is available in the file "survey-2011.csv". This also illustrates that .csv format's role as an interchange format between systems.

The field names in the table are: Timestamp (Google surveys put this in automatically), color, tv, movie, sport, book, soda. The convertToLowerCase() function of the table changes all the text it contains to lower case. This simplifies our logic, so we don't have to worry if someone typed in "Blue" or "blue" .. in the table it will always be the lowercase "blue" form.

Table Exercise

Write code to print the rows of people with favorite color "red". Run the code again, but counting "blue". (Optional) You can try the two-counter technique above to count multiple things with one loop.

Aux Table Code

aux1 (starts out with sample CSV data)



This work was created by Nick Parlante and is released under the Creative Commons Share-Alike license 3.0