Zoo tutorials: [ SQL | Linux | XML ]
ProgZoo: [ Java | C# | VB | C++ | Perl ]
Log in

A Gentle Introduction to
C++ Programming

Tutorial: Counting countries

 
You may find the page on accumulating variables useful:

1. How many countries in Asia?


Big

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.
  •     int acc = 0;
  • Every time we encounter Africa we increment acc.
  •       if (line.contains("Africa"))
          {
            acc++;
          }
  • After the loop has completed acc contains the value we want - so we print it.
  •     System.out.println(acc);

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

increment
Getting 41 countries?

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.

2. How many big countries?


Big

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

3. Numbering countries.


Big

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.

4. Country number 42.


Big

Print the name of country number 42