Table-5 Counting

< CS101

Counting

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:

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:

Experiment solutions:

If logic inside the loop:

  // 1
  // It still produces the count: NN output, just without all the row printing first.

  // 2
  // count names starting with "X" (then change to "Y")
  if (row.getField("name").startsWith("X")) {
    count = count + 1;
  }

  // 3
  // count girl names beginning with "A" (then change "girl" to "boy")
  if (row.getField("name").startsWith("A") &&
      row.getField("gender") == "girl") {
    count = count + 1;
  }

  // 4
  // resets count to 0 each time a row passes the if-filter
  // After setting to 0, increments to 1
  // always prints "count: 1"
  table = new SimpleTable("baby-2010.csv");
  for (row: table) {
      if (row.getField("name").startsWith("A")) {
          count = 0;
          count = count + 1;  // increases the value in count by 1
      }
  }
  print("count:", count);

  // 5
  // prints the count each time after it's incremented
  // count: 1, then count: 2, etc.
  table = new SimpleTable("baby-2010.csv");
  count = 0;
  for (row: table) {
      if (row.getField("name").startsWith("A")) {
          count = count + 1;  // increases the value in count by 1
          print("count:", count);
      }
  }

> exercises