Bifalgorithm post · Computer science one · Paying the Piper

How do nested for loops execute in PHP?

How do nested for loops execute in PHP? (Computer science one · Paying the Piper) — "Recall that you can write loops within loops. The inner loop will execute…

Ideas in this flowchart

  • Boucles imbriquées en PHP
  • La boucle interne s’exécute entièrement pour chaque itération de la boucle externe.
  • Exemple PHP de deux boucles imbriquées
  • La boucle externe parcourt i = 0, 1, 2, …, 9 avec n = 10.
  • La boucle interne parcourt j = 0, 1, 2, …, 19 avec m = 20.
  • printf() affiche la paire de valeurs (i, j).
  • Comptage des exécutions
  • La boucle interne effectue 20 itérations pour chaque itération de la boucle externe.
  • La boucle externe effectue 10 itérations.
  • L’instruction printf() s’exécute au total 10 × 20 = 200 fois.
  • La sortie contient les paires de (0, 0) à (9, 19), dans l’ordre des itérations.
Feed/

How do nested for loops execute in PHP?

No cover

Channel

Computer science one

1 page

"Recall that you can write loops within loops. The inner loop will execute fully for each iteration of the outer loop. An example of two nested of loops in PHP can be found in Code Sample 39.7.\n\n$n = 10;\n\n$m = 20;\n\nfor($i=0; $i<$n; $i++) {\n\nfor($j=0; $j<$m; $j++) {\n\nprintf(\"(i, j) = (%d, %d)\n\n\", $i, $j);\n\n}\n\n}\n\nThe inner loop executes for j = 0, 1, 2, . . . , 19 < m = 20 for a total of 20 iterations. However, it executes 20 times for each iteration of the outer loop. Since the outer loop executes for i = 0, 1, 2, . . . , 9 < n = 10, the total number of times the printf() statement executes is 10 × 20 = 200. In this example, the sequence (0, 0), (0, 1), (0, 2), . . . , (0, 19), (1, 0), . . . , (9, 19) will be printed."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.