Aller au contenu principal

for imbriqué

Une boucle peut être imbriquée dans une autre boucle. Chaque boucle a sa propre condition et son propre compteur.

for (initialisation ; condition ; incrémentation ou décrémentation)
{
instruction; //il n'y a pas toujours des instructions avant la boucle interne
for (initialisation ; condition ; incrémentation ou décrémentation)
{
instruction;
} // fin de la boucle interne
instruction; //il n'y a pas toujours des instructions après la boucle interne

} // fin de la boucle externe
Exemple #1 : 2 for imbriqués - Écrire les nombres de 0 à 5 sur 3 lignes différentes.Résultats
for (int cptLignes = 1; cptLignes <= 3; cptLignes ++)
{
for (int nombre = 0; nombre < 6; nombre ++)
{
Console.Write(nombre + " ");
}
Console.WriteLine();
}
0 1 2 3 4 5
0 1 2 3 4 5
0 1 2 3 4 5
Exemple #2 : 2 for imbriqués - Écrire les nombres de 0 à 6 sur 4 lignes différentes.Résultats
for (int cptLignes = 1; cptLignes <= 4; cptLignes ++)
{
Console.WriteLine("Ligne # " + cptLignes);
for (int cptColonnes = 0; cptColonnes < 7 ; cptColonnes ++)
{
Console.Write( ":" + cptColonnes);
}
Console.WriteLine(" ::");
}
Ligne #1
:0:1:2:3:4:5:6 ::
Ligne #2
:0:1:2:3:4:5:6 ::
Ligne #3
:0:1:2:3:4:5:6 ::
Ligne #4
:0:1:2:3:4:5:6 ::
Exemple #3 : - 2 for imbriqués - Écrire 4 lignes de 5 nombres,
Le premier nombre à afficher est 10
et augmente de 2 à chaque passage dans la boucle interne.
Résultats
int nombreAAfficher = 10;

for (int cptLignes = 1; cptLignes <= 4; cptLignes ++)
{
for (int cptNombres = 1; cptNombres <= 5; cptNombres ++)
{
Console.Write(nombreAAfficher + " ");
nombreAAfficher += 2;
}
Console.WriteLine();
}
10 12 14 16 18
20 22 24 26 28
30 32 34 36 38
40 42 44 46 48
Exemple #4 : - 3 for imbriqués - Écrire 3 groupes de 4 lignes identiques.
Une ligne est composée de 4 colonnes.
Chaque colonne contient le numéro de ligne suivi
du numéro de colonne suivi de : suivi d'un espace.
Exemple : L1C1: L1C2: L1C3: L1C4:
Résultats
for (int cptGroupes = 1; cptGroupes <= 3; cptGroupes ++)
{
Console.WriteLine("Groupe : " + cptGroupes);

for (int cptLignes = 1; cptLignes <= 4; cptLignes ++)
{
for (int cptColonnes = 1; cptColonnes <= 4; cptColonnes ++)
{
Console.Write("L" + cptLignes + "C" + cptColonnes + ": ");
}
Console.WriteLine();
}
Console.WriteLine("- - - - - - - - - - - - - - ");
}
L1C1: L1C2: L1C3: L1C4:
L2C1: L2C2: L2C3: L2C4:
L3C1: L3C2: L3C3: L3C4:
L4C1: L4C2: L4C3: L4C4:
- - - - - - - - - - - - - -
Groupe : 2
L1C1: L1C2: L1C3: L1C4:
L2C1: L2C2: L2C3: L2C4:
L3C1: L3C2: L3C3: L3C4:
L4C1: L4C2: L4C3: L4C4:
- - - - - - - - - - - - - -
Groupe : 3
L1C1: L1C2: L1C3: L1C4:
L2C1: L2C2: L2C3: L2C4:
L3C1: L3C2: L3C3: L3C4:
L4C1: L4C2: L4C3: L4C4:
- - - - - - - - - - - - - -