PHP:Accumulator Counting Tutorial

From Progzoo
Jump to: navigation, search

You may find the page on accumulating variables useful:

How many countries in Asia?


In this example we use an accumulator to count the countries in Africa. Notice that $acc shows up three times:

  • The accumulator $acc is set to zero at the start.
$acc = 0;
  • Every time we encounter Africa we increment $acc.
  if ($region == "Africa")
  {
    $acc++;
  }
  • After the loop has completed $acc contains the value we want - so we print it.
print $acc;

Change the program so that it counts the countries of Asia. Do NOT include the countries of Southeast Asia.

The accumulating variable is a very common trick in programming. The accumulator builds up the values - so that it is "right-so-far". For example in this program $acc always holds the number of countries in Africa in the lines that have been read so far.

[Font] [Default] [Show] [Resize] [History] [Profile]

How many big countries?


The example program counts the countries that have a population of more than 200 million.

Count the number of countries with an area of more than 1500000.

[Font] [Default] [Show] [Resize] [History] [Profile]

Numbering countries.


Produce a numbered list of countries:

1 Afghanistan
2 Albania
3 Algeria
...
262 Zimbabwe

Use three character spaces for the number and put a single space after it.

[Font] [Default] [Show] [Resize] [History] [Profile]

Country number 42.


Print the name of country number 42

[Font] [Default] [Show] [Resize] [History] [Profile]