Open In App

Foreach in C++ and Java

Last Updated : 29 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Foreach loop is used to iterate over the elements of a container (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 support the 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_name) {

     operations using variable_name

}

With the introduction of auto keyword in C++ and var keyword in Java, we no longer need to specify the 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.

The 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. 

Java Program for ArrayList:

Java




/*package whatever //do not write package name here */
 
import java.util.*;
 
class GFG {
    public static void main(String[] args)
    {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(3);
        list.add(24);
        list.add(-134);
        list.add(-2);
        list.add(100);
        for (int element : list) {
            System.out.print(element + " ");
        }
    }
}


Output

3 24 -134 -2 100 

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.


Previous Article
Next Article

Similar Reads

foreach() loop vs Stream foreach() vs Parallel Stream foreach()
foreach() loopLambda operator is not used: foreach loop in Java doesn't use any lambda operations and thus operations can be applied on any value outside of the list that we are using for iteration in the foreach loop. The foreach loop is concerned over iterating the collection or array by storing each element of the list on a local variable and do
4 min read
Difference Between Collection.stream().forEach() and Collection.forEach() in Java
Collection.forEach() and Collection.stream().forEach() are used for iterating over the collections, there is no such major difference between the two, as both of them give the same result, though there are some differences in their internal working. Collection.stream().forEach() is basically used for iteration in a group of objects by converting a
3 min read
Java Program to Iterate Over Arrays Using for and foreach Loop
An array is a group of like-typed variables that are referred to by a common name. Arrays in Java work differently than they do in C/C++. Here, we have explained the for loop and foreach loop to display the elements of an array in Java. 1. For Loop:For-loop provides a concise way of writing the loop structure. A for statement consumes the initializ
4 min read
Stream forEach() method in Java with examples
Stream forEach(Consumer action) performs an action for each element of the stream. Stream forEach(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. Syntax : void forEach(Consumer&lt;? super T&gt; action) Where, Consumer is a functional interface and T is the type of stream elements. Note
2 min read
IntStream forEach() method in Java
IntStream forEach(IntConsumer action) performs an action for each element of the stream. IntStream forEach(IntConsumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. Syntax : void forEach(IntConsumer action) Parameter : IntConsumer represents an operation that accepts a single int-valued argume
2 min read
Iterable forEach() method in Java with Examples
It has been Quite a while since Java 8 released. With the release, they have improved some of the existing APIs and added few new features. One of them is forEach Method in java.lang.Iterable Interface. Whenever we need to traverse over a collection we have to create an Iterator to iterate over the collection and then we can have our business logic
3 min read
ArrayList forEach() method in Java
The forEach() method of ArrayList used to perform the certain operation for each element in ArrayList. This method traverses each element of the Iterable of ArrayList until all elements have been Processed by the method or an exception is raised. The operation is performed in the order of iteration if that order is specified by the method. Exceptio
2 min read
Vector forEach() method in Java
The forEach() method of Vector is used to perform a given action for every element of the Iterable of Vector until all elements have been Processed by the method or an exception occurs. The operations are performed in the order of iteration if the order is specified by the method. Exceptions thrown by the Operation are passed to the caller. Until a
3 min read
Flatten a Stream of Lists in Java using forEach loop
Given a Stream of Lists in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: lists = [ [1, 2], [3, 4, 5, 6], [8, 9] ] Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: lists = [ ['G', 'e', 'e', 'k', 's'], ['F', 'o', 'r'] ] Output: [G, e, e, k, s, F, o, r] Approach: Get the Lists in the form of 2D list. Create an empty list t
3 min read
Flatten a Stream of Arrays in Java using forEach loop
Given a Stream of Arrays in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: arr[][] = {{ 1, 2 }, { 3, 4, 5, 6 }, { 7, 8, 9 }} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: arr[][] = {{'G', 'e', 'e', 'k', 's'}, {'F', 'o', 'r'}} Output: [G, e, e, k, s, F, o, r] Approach: Get the Arrays in the form of 2D array. Create an
3 min read
Article Tags :
Practice Tags :