- 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++ 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
Advertisements