Foreach in C++ vs Java

C++Server Side ProgrammingProgramming

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


raja
Published on 29-Apr-2019 13:07:03
Advertisements