Counter
tags: counter up-counter down-counter
Counter is a variable used to count something. It is usually initialized to zero and then incremented when some criteria is met.
Counting with Array
Write a program to count the number of times a character appears in a given word.
|
|
This program illustrates a basic building block: counter. The counter variable count is initialized to 0 and it is incremented whenever there is a match in the word for the given character that needs to be counted.
After the loop terminates the counter variable has the number of occurrences of the given character in the word.
The string needs to be converted to a sequence of character by using the chars method. This returns an array of characters. After the conversion an index which is an integer value is used to select an item in the sequence, such as a character in the input string.
Counting with Linked List
A while loop can be used for counting. The example code shows how to count the number of nodes in a linked list.
|
|
It is a good practice to use a current pointer that moves through the linked list instead of changing the input object passed to the count method.
Recursive Counting in Linked List
The base case is reached when we reach the end of the linked list. The input to the count recursive function traverses the linked list one node at a time.
|
|
The counter can be classified as either up counter or down counter. For example counting from 1 to 10 is up counter and counting down from 10 to 1 is down counter. In some languages you can use the for loop to count both up and down. In Ruby down counter is provided by downto method.