Foreach in C++ and Java


In C++ and Java, there are another type of loop called foreach loop. This is not present in C. This loop has introduced in C++11 and Java JDK 1.5.0. The advantage of this loop is that, it can access the elements very quickly without performing initialization, testing and increment/decrement. This loop is used to access every element in one array or some containers. This loop is known as foreach but to denote this loop we have to use ‘for’ keyword. The syntax is different than normal for and foreach.

for(datatype item : Array) {
}

Let us see some examples of foreach loop in C++ and Java.

Live Demo For C++

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int myArr[] = { 99, 15, 67 };
   // foreach loop
   for (int ele : myArr)
      cout << ele << endl;
}

Output

99
15
67

Live Demo For Java

Example

 Live Demo

public class Test {
   public static void main(String args[]) {
      int [] numbers = {10, 20, 30, 40, 50};
      for(int x : numbers ) {
         System.out.print( x );
         System.out.print(",");
      }
      System.out.print("\n");
      String [] names = {"James", "Larry", "Tom", "Lacy"};
      for( String name : names ) {
         System.out.print( name );
         System.out.print(",");
      }
   }
}

Output

10, 20, 30, 40, 50,
James, Larry, Tom, Lacy,

Updated on: 30-Jul-2019

109 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements