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


Updated on: 30-Jul-2019

165 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements