
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
Foreach in C++ and C#
Foreach in C++
C++ 11 introduced foreach loop to traverse over each element. Here is an example −
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
Foreach in C#
Let us see an example of foreach in C#. It traverses items in a collection −
Example
using System; namespace ArrayApplication { class MyArray { static void Main(string[] args) { int [] n = new int[10]; /* n is an array of 10 integers */ for ( int i = 0; i < 10; i++ ) { n[i] = i + 100; } /* output each array element's value */ foreach (int j in n ) { int i = j-100; Console.WriteLine("Element[{0}] = {1}", i, j); } Console.ReadKey(); } } }
Output
Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109
- Related Articles
- Foreach in C++ and Java
- foreach Loop in C#
- Foreach in C++ vs Java
- Using foreach loop in arrays in C#
- Iterating C# StringBuilder in a foreach loop
- What is the difference between Foreach and Parallel.Foreach in C#?
- How do you use ‘foreach’ statement for accessing array elements in C#
- How do you use ‘foreach’ loop for iterating over an array in C#?
- How to iterate two Lists or Arrays with one foreach statement in C#?
- How do I copy items from list to list without foreach in C#?
- foreach in Java
- Difference Between For and Foreach in PHP
- Difference between Collection.stream().forEach() and Collection.forEach() in Java
- How do we use foreach statement to loop through the elements of an array in C#?
- How to use for and foreach loop in Golang?

Advertisements