- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
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,
Advertisements