Skip to content
Related Articles

Related Articles

Foreach in C++ and Java
  • Difficulty Level : Easy
  • Last Updated : 25 Nov, 2019

Foreach loop is used to access elements of an array 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.

C++ Program:




// C++ program to demonstrate use of foreach
#include <iostream>
using namespace std;
  
int main()
{
    int arr[] = { 10, 20, 30, 40 };
  
    // Printing elements of an array using
    // foreach loop
    for (int x : arr)
        cout << x << endl;
}
Output:



10
20
30
40

Java program




// 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
        for (int x : arr)
            System.out.println(x);
    }
}
Output:
10
20
30
40

Advantages of Foreach loop:-
1) Makes code more readable.
2) Eliminates the possibility of programming errors.

This article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :