Skip to content
Related Articles

Related Articles

Foreach in C++ and Java

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 09 Jun, 2022

Foreach loop is used to iterate over the elements of a containers (array, vectors etc) quickly without performing initialization, testing and increment/decrement. The working of foreach loops is to do something for every element rather than doing something n times. There is no foreach loop in C, but both C++ and Java have support for foreach type of loop. In C++, it was introduced in C++ 11 and Java in JDK 1.5.0 The keyword used for foreach loop is “for” in both C++ and Java.  

Syntax:

for (data_type  variable_name : container_type) {

     operations using variable_name

}

With the introduction of auto keyword in C++ and var keyword in Java, we no longer need to specify data type for the variable in foreach loop. Type inference detects the data type of the container and automatically sets the same data type to the variable used for traversing.

Below code displays the use case of foreach loop for different containers along with auto/var keywords in C++/Java

C++/Java Program for array: 

C++




// C++ program to demonstrate use of foreach for array
#include <iostream>
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<<"Traversing the array with foreach using array's data type: ";
    for (int x : arr)
        cout<<x<<" ";
       
      // data type of x is set as int
    cout<<"\nTraversing the array with foreach using auto keyword     : ";
      for (auto x : arr)
      cout<<x<<" ";
}


Java




// 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("Traversing the array with foreach using array's data type: ");
        for (int x : arr)
            System.out.print(x+" ");
       
        // data type of x is set as int
          System.out.print("\nTraversing the array with foreach using auto keyword     : ");
          for (var x : arr)
              System.out.print(x+" ");
    }
}


Output

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

C++ Program for vector:

C++




#include <iostream>
#include <vector>
using namespace std;
 
int main() {
 
      vector<string> value{"This", "is", "foreach", "example", "using", "vector."};
     
    cout<<"Traversing the vector with foreach using vector's data type: ";
    for (string v : value) {
        cout<<v<<" ";
    }
 
    cout<<"\nTraversing the vector with foreach using auto keyword      : ";
      for (auto v : value)
      cout<<v<<" ";
    return 0;
}


Output

Traversing the vector with foreach using vector's data type: This is foreach example using vector. 
Traversing the vector with foreach using auto keyword      : This is foreach example using vector. 

C++/Java Program for set:

C++




#include <iostream>
#include <set>
using namespace std;
 
int main() {
 
    set<int> value = {6, 2, 7, 4, 10, 5, 1};
   
    cout<<"Traversing the set with foreach using set's data type: ";
      for (int v : value) {
        cout<<v<<" ";
    }
   
    cout<<"\nTraversing the set with foreach using auto keyword   : ";
      for (auto v : value)
      cout<<v<<" ";
   
    return 0;
}


Java




import java.util.*;
   
public class GFG {
     
    public static void main(String[] args)
    {
        Set<String> hash_Set = new HashSet<String>();
        hash_Set.add("Geeks");
        hash_Set.add("For");
        hash_Set.add("Geeks");
        hash_Set.add("Foreach");
        hash_Set.add("Example");
        hash_Set.add("Set");
   
        System.out.print("Traversing the set with foreach using set's data type: ");
        for(String hs : hash_Set) {
            System.out.print(hs+" ");
        }
       
          System.out.print("\nTraversing the set with foreach using auto keyword   : ");
        for (var hs : hash_Set) {
            System.out.print(hs+" ");
        }
           
    }
}


Output

Traversing the set with foreach using set'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 

Note: We can use different data types in foreach for array, vector and set.

C++/Java Program for map:

C++14




#include <iostream>
#include <map>
using namespace std;
 
int main() {
 
      map<int, string> mapExample;
    mapExample.insert(pair<int, string>(1, "Geeks"));
    mapExample.insert(pair<int, string>(2, "4"));
    mapExample.insert(pair<int, string>(3, "Geeks"));
    mapExample.insert(pair<int, string>(4, "Map"));
      mapExample.insert(pair<int, string>(5, "Foreach"));
    mapExample.insert(pair<int, string>(6, "Example"));
   
    cout<<"Traversing the map with foreach using map's data type\n";
      for (pair<int, string> mpEx : mapExample ) {
        cout<<mpEx.first<<" "<<mpEx.second<<endl;
    }
   
    cout<<"\nTraversing the map with foreach using auto keyword\n";
      for (auto mpEx : mapExample){
        cout<<mpEx.first<<" "<<mpEx.second<<endl;
    }
   
    return 0;
}


Java




import java.io.*;
import java.util.Map;
import java.util.HashMap;
 
class GFG {
    public static void main (String[] args) {
        Map<Integer,String> gfg = new HashMap<Integer,String>();
       
        gfg.put(1, "Geeks");
        gfg.put(2, "4");
        gfg.put(3, "Geeks");
          gfg.put(4, "Map");
        gfg.put(5, "Foreach");
        gfg.put(6, "Example");
   
        System.out.println("Traversing the map with foreach using map's data type");
        for (Map.Entry<Integer, String> entry : gfg.entrySet())
                System.out.println(entry.getKey() + " " + entry.getValue());
       
          System.out.println("\nTraversing the map with foreach using auto keyword");
          for (var entry : gfg.entrySet())
                System.out.println(entry.getKey() + " " + entry.getValue());
    }
}


Output

Traversing the map with foreach using map'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

Advantages of foreach loop:

  •  Makes the code more readable. 
  •  Eliminates the errors of over-running or under-running the data.

Disadvantage of foreach loop:

  • Cannot iterate over the elements in reverse order.
  • Each and every element will be accessed, cannot skip any elements in between.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!