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 Jave support 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.
10 20 30 40
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 email@example.com. 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
- Iterator vs Foreach In Java
- IntStream forEach() method in Java
- LongStream forEach() method in Java
- DoubleStream forEach() method in Java
- Vector forEach() method in Java
- ArrayDeque forEach() method in Java
- ArrayList forEach() method in Java
- Stream forEach() method in Java with examples
- HashTable forEach() method in Java with Examples
- Flatten a Stream of Map in Java using forEach loop
- Flatten a Stream of Arrays in Java using forEach loop
- Flatten a Stream of Lists in Java using forEach loop
- Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
- Java lang.Long.highestOneBit() method in Java with Examples
- Java lang.Long.reverse() method in Java with Examples
Improved By : gyanendra371