Skip to content

Count occurrences

TypeScript loop + counter

Flowchart (ISO 5807)

YesNoStartInput a, keycount = 0i = 0, |a| − 1, 1a[i] = keycount = count + 1Return countEndFigure 1 — countOccurrences

Source code

TypeScript
function countOccurrences(a: number[], key: number): number {
    let count = 0;
    for (let i = 0; i < a.length; i++) {
        if (a[i] === key) {
            count++;
        }
    }
    return count;
}

The editor opens with this code — change it and the chart redraws.

Language
TypeScript
Constructs
loop + counter
Topic
Loops
Formats
Word, Visio, draw.io, PDF, SVG

Related examples