For Each Loop in C++ Programming


The enhanced style for can only cycle through an array sequentially, from start to finish.It is also known as the for each loop. The enhanced for loop was introduced in c++ as a simpler way to iterate through all the elements of a Collection (Collections are not covered in these pages). It can also be used for arrays, as in the above example, but this is not the original purpose. The for each loops are simple but inflexible. They can be used when you wish to step through the elements of the array in first-to-last order, and you do not need to know the index of the current element.

Syntax:
   for( Datatype item : array )
   {
        // body of loop;
   }

The program is written in C++ programming language and it displays the elements of an integer array using a range-based for loop. Here's a step-by-step explanation of the program:

  • #include<iostream> - This is a preprocessor directive that includes the iostream header file in the program. This file provides input and output operations in C++.
  • using namespace std; - This statement tells the compiler to use the standard namespace, which contains the standard C++ library.
  • int main() - This is the starting point of the program. The main() function is the entry point for all C++ programs.
  • int a[]={65,66,67,68,69,70}; - This statement declares an integer array named "a" and initializes it with the values 65, 66, 67, 68, 69, and 70.
  • for(auto x : a) - This is a range-based for loop that iterates over each element of the array "a". The variable "x" takes on the value of each element in the array, one at a time.
  • cout<<x<<endl; - This statement prints the value of each element in the array "a" to the console, followed by a newline character.
  • return 0; - This statement ends the program and returns the value 0 to the operating system. The value 0 indicates that the program executed successfully.

Source Code

//For Each
#include<iostream>
using namespace std;
int main()
{
    int a[]={65,66,67,68,69,70};
   for(auto x : a)
   {
       cout<<x<<endl;
   }
     return 0;
}
 

Output

65
66
67
68
69
70
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples