
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Foreach in C++ vs Java
In C++ and Java, there is another kind of loop, called the foreach loop. This is basically a modification of for loop. This loop is used to access the data from some container. This can access the elements of some array quickly without performing initialization. This loop is used to do something for each element of a container, not doing things n times.
Now let us see how the foreach loop is used in C++ and Java.
Example
#include <iostream> using namespace std; int main() { int arr[] = { 11, 22, 33, 44, 55, 66, 77, 88, 99 }; for (int a : arr) //foreach loop cout << a << endl; }
Output
11 22 33 44 55 66 77 88 99
Example
public class Test { public static void main(String[] args) { int arr[] = { 11, 22, 33, 44, 55, 66, 77, 88, 99 }; for (int a : arr) System.out.println(a); } }
Output
11 22 33 44 55 66 77 88 99
- Related Articles
- Iterator vs forEach in Java
- Performance of FOR vs FOREACH in PHP
- foreach in Java
- IntStream forEach() method in Java
- LongStream forEach() method in Java
- DoubleStream forEach() method in Java
- Foreach in C++ and Java
- Difference between Collection.stream().forEach() and Collection.forEach() in Java
- Set vs HashSet vs TreeSet in Java
- C++ vs Java vs Python?
- How does the Java “foreach” loop work?
- equals() vs == in Java
- Cplus plus vs Java vs Python?
- Inheritance in C++ vs Java
- Iterator vs ListIterator in Java?

Advertisements