A function that remembers how many times it was called, using a static variable.
What to build
A program that gives each name a running number.
Requirements
- Write a function
nextId()that returns 1 the first time, 2 the second time, and so on. - Read n and then n names. For each name print
ID: NAMEwith the next id.
Input
Line 1: n. Then n lines with one name each.
Output
n lines.
Constraints
1 ≤ n ≤ 50.
Example
Input:
3
Ada
Bo
Cy
Output:
1: Ada
2: Bo
3: Cy
Why it works
The static variable is created once and keeps its value, so each call continues where the last one stopped.
Examples
Example 1 · Input
3 Ada Bo Cy
Expected output
1: Ada 2: Bo 3: Cy
Example 2 · Input
1 Solo
Expected output
1: Solo
Hints
Hint 1
A static variable keeps its value between calls: static $id = 0;
Hint 2
Add one to it and return it every time the function is called.
Solution
Show one correct solution (try it yourself first)
<?php
function nextId(): int
{
static $id = 0;
$id++;
return $id;
}
$n = (int) trim(fgets(STDIN));
for ($i = 0; $i < $n; $i++) {
$name = trim(fgets(STDIN));
echo nextId(), ": ", $name, "\n";
}