logo

Foreach en C++ et JAVA

La boucle foreach est utilisée pour parcourir rapidement les éléments d'un conteneur (tableau, vecteurs, etc.) sans effectuer d'initialisation, de test ou d'incrémentation/décrémentation. Les boucles Foreach fonctionnent en faisant quelque chose pour chaque élément plutôt qu'en faisant quelque chose n fois. Bien qu'il n'y ait pas de boucle foreach en C, elle est prise en charge par C++ et Java. Il a été introduit pour la première fois en C++ dans C++ 11 et en Java dans JDK 1.5.0. En C++ et Java, le mot-clé de la boucle foreach est « for ».

Syntaxe

 for (data_type variable_name : container_type) { operations using variable_name } 

Nous n'avons plus besoin de spécifier le type de données des variables dans les boucles foreach grâce à l'introduction du mot-clé auto en C++ et du mot-clé var en Java. L'inférence de type détecte le type de données du conteneur et définit la variable utilisée pour le parcours vers le même type de données.

Le code ci-dessous démontre l'utilisation d'une boucle foreach pour divers conteneurs, ainsi que les mots-clés auto/var en C++/Java.

C++

 // C++ program to demonstrate use of foreach for array #include using namespace std; int main() { int arr[] = { 10, 20, 30, 40 }; // Printing elements of an array using // foreach loop // Here, int is the data type, x is the variable name // and arr is the array for which we want to iterate foreach cout&lt;<'traversing the array with foreach using array's data type: '; for (int x : arr) cout<<x<<' type of is set as int cout<<'
traversing auto keyword (auto } < pre> <h3>JAVA</h3> <pre> // Java program to demonstrate use of foreach public class Main { public static void main(String[] args) { // Declaring 1-D array with size 4 int arr[] = { 10, 20, 30, 40 }; // Printing elements of an array using // foreach loop // Here, int is the data type, x is the variable name // and arr is the array for which we want to iterate foreach System.out.print(&apos;Traversing the array with foreach using array&apos;s data type: &apos;); for (int x : arr) System.out.print(x+&apos; &apos;); // data type of x is set as int System.out.print(&apos;
Traversing the array with foreach using auto keyword : &apos;); for (var x : arr) System.out.print(x+&apos; &apos;); } } </pre> <p> <strong>Output</strong> </p> <pre> Traversing the array with foreach using array&apos;s data type: 10 20 30 40 Traversing the array with foreach using auto keyword : 10 20 30 40 </pre> <h3>Vector C++ programme:</h3> <pre> #include #include using namespace std; int main() { vector value{&apos;This&apos;, &apos;is&apos;, &apos;foreach&apos;, &apos;example&apos;, &apos;using&apos;, &apos;vector.&apos;}; cout&lt;<'traversing the vector with foreach using vector's data type: '; for (string v : value) { cout<<v<<' } cout<<'
traversing auto keyword (auto return 0; < pre> <p> <strong>Output</strong> </p> <pre> Traversing the vector with foreach using vector&apos;s data type: This is foreach example using vector. Traversing the vector with foreach using auto keyword : This is foreach example using vector. </pre> <h2>C++/Java Set Program:</h2> <h3>C++</h3> <pre> #include #include using namespace std; int main() { set value = {6, 2, 7, 4, 10, 5, 1}; cout&lt;<'traversing the set with foreach using set's data type: '; for (int v : value) { cout<<v<<' } cout<<'
traversing auto keyword (auto return 0; < pre> <h3>JAVA</h3> <pre> import java.util.*; public class GFG { public static void main(String[] args) { Set hash_Set = new HashSet(); hash_Set.add(&apos;Geeks&apos;); hash_Set.add(&apos;For&apos;); hash_Set.add(&apos;Geeks&apos;); hash_Set.add(&apos;Foreach&apos;); hash_Set.add(&apos;Example&apos;); hash_Set.add(&apos;Set&apos;); System.out.print(&apos;Traversing the set with foreach using set&apos;s data type: &apos;); for(String hs : hash_Set) { System.out.print(hs+&apos; &apos;); } System.out.print(&apos;
Traversing the set with foreach using auto keyword : &apos;); for (var hs : hash_Set) { System.out.print(hs+&apos; &apos;); } } } </pre> <p> <strong>Output</strong> </p> <pre> Traversing the set with foreach using set&apos;s data type: 1 2 4 5 6 7 10 Traversing the set with foreach using auto keyword : 1 2 4 5 6 7 10 </pre> <p>For array, vector, and set, we can use different data types in foreach.</p> <h2>C++/Java Map Program:</h2> <h3>C++</h3> <pre> #include #include using namespace std; int main() { map mapExample; mapExample.insert(pair(1, &apos;Geeks&apos;)); mapExample.insert(pair(2, &apos;4&apos;)); mapExample.insert(pair(3, &apos;Geeks&apos;)); mapExample.insert(pair(4, &apos;Map&apos;)); mapExample.insert(pair(5, &apos;Foreach&apos;)); mapExample.insert(pair(6, &apos;Example&apos;)); cout&lt;<'traversing the map with foreach using map's data type
'; for (pair mpex : mapexample ) { cout<<mpex.first<<' '<<mpex.second<<endl; } cout<<'
traversing auto keyword
'; (auto mapexample){ return 0; < pre> <h3>JAVA</h3> <pre> import java.io.*; import java.util.Map; import java.util.HashMap; class GFG { public static void main (String[] args) { Map gfg = new HashMap(); gfg.put(1, &apos;Geeks&apos;); gfg.put(2, &apos;4&apos;); gfg.put(3, &apos;Geeks&apos;); gfg.put(4, &apos;Map&apos;); gfg.put(5, &apos;Foreach&apos;); gfg.put(6, &apos;Example&apos;); System.out.println(&apos;Traversing the map with foreach using map&apos;s data type&apos;); for (Map.Entry entry : gfg.entrySet()) System.out.println(entry.getKey() + &apos; &apos; + entry.getValue()); System.out.println(&apos;
Traversing the map with foreach using auto keyword&apos;); for (var entry : gfg.entrySet()) System.out.println(entry.getKey() + &apos; &apos; + entry.getValue()); } } </pre> <p> <strong>Output</strong> </p> <pre> Traversing the map with foreach using map&apos;s data type 1 Geeks 2 4 3 Geeks 4 Map 5 Foreach 6 Example Traversing the map with foreach using auto keyword 1 Geeks 2 4 3 Geeks 4 Map 5 Foreach 6 Example </pre> <h3>Foreach loop has the following advantages:</h3> <ul> <li>This improves the readability of the code.</li> <li>Removes the possibility of data over- or under-running errors.</li> </ul> <h3>Foreach loop has the following disadvantage:</h3> <ul> <li>It is not possible to iterate over the elements in reverse order.</li> <li>Every element will be accessed; no elements in between will be skipped.</li> </ul> <hr></'traversing></pre></'traversing></pre></'traversing></pre></'traversing>

Sortir

 Traversing the array with foreach using array&apos;s data type: 10 20 30 40 Traversing the array with foreach using auto keyword : 10 20 30 40 

Programme vectoriel C++ :

 #include #include using namespace std; int main() { vector value{&apos;This&apos;, &apos;is&apos;, &apos;foreach&apos;, &apos;example&apos;, &apos;using&apos;, &apos;vector.&apos;}; cout&lt;<\'traversing the vector with foreach using vector\'s data type: \'; for (string v : value) { cout<<v<<\' } cout<<\'
traversing auto keyword (auto return 0; < pre> <p> <strong>Output</strong> </p> <pre> Traversing the vector with foreach using vector&apos;s data type: This is foreach example using vector. Traversing the vector with foreach using auto keyword : This is foreach example using vector. </pre> <h2>C++/Java Set Program:</h2> <h3>C++</h3> <pre> #include #include using namespace std; int main() { set value = {6, 2, 7, 4, 10, 5, 1}; cout&lt;<\'traversing the set with foreach using set\'s data type: \'; for (int v : value) { cout<<v<<\' } cout<<\'
traversing auto keyword (auto return 0; < pre> <h3>JAVA</h3> <pre> import java.util.*; public class GFG { public static void main(String[] args) { Set hash_Set = new HashSet(); hash_Set.add(&apos;Geeks&apos;); hash_Set.add(&apos;For&apos;); hash_Set.add(&apos;Geeks&apos;); hash_Set.add(&apos;Foreach&apos;); hash_Set.add(&apos;Example&apos;); hash_Set.add(&apos;Set&apos;); System.out.print(&apos;Traversing the set with foreach using set&apos;s data type: &apos;); for(String hs : hash_Set) { System.out.print(hs+&apos; &apos;); } System.out.print(&apos;
Traversing the set with foreach using auto keyword : &apos;); for (var hs : hash_Set) { System.out.print(hs+&apos; &apos;); } } } </pre> <p> <strong>Output</strong> </p> <pre> Traversing the set with foreach using set&apos;s data type: 1 2 4 5 6 7 10 Traversing the set with foreach using auto keyword : 1 2 4 5 6 7 10 </pre> <p>For array, vector, and set, we can use different data types in foreach.</p> <h2>C++/Java Map Program:</h2> <h3>C++</h3> <pre> #include #include using namespace std; int main() { map mapExample; mapExample.insert(pair(1, &apos;Geeks&apos;)); mapExample.insert(pair(2, &apos;4&apos;)); mapExample.insert(pair(3, &apos;Geeks&apos;)); mapExample.insert(pair(4, &apos;Map&apos;)); mapExample.insert(pair(5, &apos;Foreach&apos;)); mapExample.insert(pair(6, &apos;Example&apos;)); cout&lt;<\'traversing the map with foreach using map\'s data type
\'; for (pair mpex : mapexample ) { cout<<mpex.first<<\' \'<<mpex.second<<endl; } cout<<\'
traversing auto keyword
\'; (auto mapexample){ return 0; < pre> <h3>JAVA</h3> <pre> import java.io.*; import java.util.Map; import java.util.HashMap; class GFG { public static void main (String[] args) { Map gfg = new HashMap(); gfg.put(1, &apos;Geeks&apos;); gfg.put(2, &apos;4&apos;); gfg.put(3, &apos;Geeks&apos;); gfg.put(4, &apos;Map&apos;); gfg.put(5, &apos;Foreach&apos;); gfg.put(6, &apos;Example&apos;); System.out.println(&apos;Traversing the map with foreach using map&apos;s data type&apos;); for (Map.Entry entry : gfg.entrySet()) System.out.println(entry.getKey() + &apos; &apos; + entry.getValue()); System.out.println(&apos;
Traversing the map with foreach using auto keyword&apos;); for (var entry : gfg.entrySet()) System.out.println(entry.getKey() + &apos; &apos; + entry.getValue()); } } </pre> <p> <strong>Output</strong> </p> <pre> Traversing the map with foreach using map&apos;s data type 1 Geeks 2 4 3 Geeks 4 Map 5 Foreach 6 Example Traversing the map with foreach using auto keyword 1 Geeks 2 4 3 Geeks 4 Map 5 Foreach 6 Example </pre> <h3>Foreach loop has the following advantages:</h3> <ul> <li>This improves the readability of the code.</li> <li>Removes the possibility of data over- or under-running errors.</li> </ul> <h3>Foreach loop has the following disadvantage:</h3> <ul> <li>It is not possible to iterate over the elements in reverse order.</li> <li>Every element will be accessed; no elements in between will be skipped.</li> </ul> <hr></\'traversing></pre></\'traversing></pre></\'traversing>

Programme C++/Java :

C++

 #include #include using namespace std; int main() { set value = {6, 2, 7, 4, 10, 5, 1}; cout&lt;<\'traversing the set with foreach using set\'s data type: \'; for (int v : value) { cout<<v<<\' } cout<<\'
traversing auto keyword (auto return 0; < pre> <h3>JAVA</h3> <pre> import java.util.*; public class GFG { public static void main(String[] args) { Set hash_Set = new HashSet(); hash_Set.add(&apos;Geeks&apos;); hash_Set.add(&apos;For&apos;); hash_Set.add(&apos;Geeks&apos;); hash_Set.add(&apos;Foreach&apos;); hash_Set.add(&apos;Example&apos;); hash_Set.add(&apos;Set&apos;); System.out.print(&apos;Traversing the set with foreach using set&apos;s data type: &apos;); for(String hs : hash_Set) { System.out.print(hs+&apos; &apos;); } System.out.print(&apos;
Traversing the set with foreach using auto keyword : &apos;); for (var hs : hash_Set) { System.out.print(hs+&apos; &apos;); } } } </pre> <p> <strong>Output</strong> </p> <pre> Traversing the set with foreach using set&apos;s data type: 1 2 4 5 6 7 10 Traversing the set with foreach using auto keyword : 1 2 4 5 6 7 10 </pre> <p>For array, vector, and set, we can use different data types in foreach.</p> <h2>C++/Java Map Program:</h2> <h3>C++</h3> <pre> #include #include using namespace std; int main() { map mapExample; mapExample.insert(pair(1, &apos;Geeks&apos;)); mapExample.insert(pair(2, &apos;4&apos;)); mapExample.insert(pair(3, &apos;Geeks&apos;)); mapExample.insert(pair(4, &apos;Map&apos;)); mapExample.insert(pair(5, &apos;Foreach&apos;)); mapExample.insert(pair(6, &apos;Example&apos;)); cout&lt;<\'traversing the map with foreach using map\'s data type
\'; for (pair mpex : mapexample ) { cout<<mpex.first<<\' \'<<mpex.second<<endl; } cout<<\'
traversing auto keyword
\'; (auto mapexample){ return 0; < pre> <h3>JAVA</h3> <pre> import java.io.*; import java.util.Map; import java.util.HashMap; class GFG { public static void main (String[] args) { Map gfg = new HashMap(); gfg.put(1, &apos;Geeks&apos;); gfg.put(2, &apos;4&apos;); gfg.put(3, &apos;Geeks&apos;); gfg.put(4, &apos;Map&apos;); gfg.put(5, &apos;Foreach&apos;); gfg.put(6, &apos;Example&apos;); System.out.println(&apos;Traversing the map with foreach using map&apos;s data type&apos;); for (Map.Entry entry : gfg.entrySet()) System.out.println(entry.getKey() + &apos; &apos; + entry.getValue()); System.out.println(&apos;
Traversing the map with foreach using auto keyword&apos;); for (var entry : gfg.entrySet()) System.out.println(entry.getKey() + &apos; &apos; + entry.getValue()); } } </pre> <p> <strong>Output</strong> </p> <pre> Traversing the map with foreach using map&apos;s data type 1 Geeks 2 4 3 Geeks 4 Map 5 Foreach 6 Example Traversing the map with foreach using auto keyword 1 Geeks 2 4 3 Geeks 4 Map 5 Foreach 6 Example </pre> <h3>Foreach loop has the following advantages:</h3> <ul> <li>This improves the readability of the code.</li> <li>Removes the possibility of data over- or under-running errors.</li> </ul> <h3>Foreach loop has the following disadvantage:</h3> <ul> <li>It is not possible to iterate over the elements in reverse order.</li> <li>Every element will be accessed; no elements in between will be skipped.</li> </ul> <hr></\'traversing></pre></\'traversing>

Sortir

 Traversing the set with foreach using set&apos;s data type: 1 2 4 5 6 7 10 Traversing the set with foreach using auto keyword : 1 2 4 5 6 7 10 

Pour les tableaux, vecteurs et ensembles, nous pouvons utiliser différents types de données dans foreach.

Programme de cartographie C++/Java :

C++

 #include #include using namespace std; int main() { map mapExample; mapExample.insert(pair(1, &apos;Geeks&apos;)); mapExample.insert(pair(2, &apos;4&apos;)); mapExample.insert(pair(3, &apos;Geeks&apos;)); mapExample.insert(pair(4, &apos;Map&apos;)); mapExample.insert(pair(5, &apos;Foreach&apos;)); mapExample.insert(pair(6, &apos;Example&apos;)); cout&lt;<\\'traversing the map with foreach using map\\'s data type
\\'; for (pair mpex : mapexample ) { cout<<mpex.first<<\\' \\'<<mpex.second<<endl; } cout<<\\'
traversing auto keyword
\\'; (auto mapexample){ return 0; < pre> <h3>JAVA</h3> <pre> import java.io.*; import java.util.Map; import java.util.HashMap; class GFG { public static void main (String[] args) { Map gfg = new HashMap(); gfg.put(1, &apos;Geeks&apos;); gfg.put(2, &apos;4&apos;); gfg.put(3, &apos;Geeks&apos;); gfg.put(4, &apos;Map&apos;); gfg.put(5, &apos;Foreach&apos;); gfg.put(6, &apos;Example&apos;); System.out.println(&apos;Traversing the map with foreach using map&apos;s data type&apos;); for (Map.Entry entry : gfg.entrySet()) System.out.println(entry.getKey() + &apos; &apos; + entry.getValue()); System.out.println(&apos;
Traversing the map with foreach using auto keyword&apos;); for (var entry : gfg.entrySet()) System.out.println(entry.getKey() + &apos; &apos; + entry.getValue()); } } </pre> <p> <strong>Output</strong> </p> <pre> Traversing the map with foreach using map&apos;s data type 1 Geeks 2 4 3 Geeks 4 Map 5 Foreach 6 Example Traversing the map with foreach using auto keyword 1 Geeks 2 4 3 Geeks 4 Map 5 Foreach 6 Example </pre> <h3>Foreach loop has the following advantages:</h3> <ul> <li>This improves the readability of the code.</li> <li>Removes the possibility of data over- or under-running errors.</li> </ul> <h3>Foreach loop has the following disadvantage:</h3> <ul> <li>It is not possible to iterate over the elements in reverse order.</li> <li>Every element will be accessed; no elements in between will be skipped.</li> </ul> <hr></\\'traversing>

Sortir

 Traversing the map with foreach using map&apos;s data type 1 Geeks 2 4 3 Geeks 4 Map 5 Foreach 6 Example Traversing the map with foreach using auto keyword 1 Geeks 2 4 3 Geeks 4 Map 5 Foreach 6 Example 

La boucle Foreach présente les avantages suivants :

  • Cela améliore la lisibilité du code.
  • Supprime la possibilité d’erreurs de dépassement ou de sous-exécution des données.

La boucle Foreach présente l'inconvénient suivant :

  • Il n'est pas possible de parcourir les éléments dans l'ordre inverse.
  • Chaque élément sera accessible ; aucun élément intermédiaire ne sera ignoré.