C# Foreach Loops :

foreach loop :

The foreach loop (extended for-loop) is new for the C Language/C++ Language/C# Language family of languages, but is well known for the VB and PHP programmers. This programming construct serves to iterate over all elements of an array, list or other collection of elements (IEnumerable). It passes through all the elements of the specified collection even if the collection is not indexed.

Syntax :

foreach (type variable in collection)
{
statements;
}


Example :

  1. /* Description: print 'int' or 'string' values use foreach in C Sharp language */
  2. using System;
  3. namespace DemoProgramming
  4. {
  5. class Program
  6. {
  7. static void Main()
  8. {
  9. int[] numbers = { 1, 2, 3, 4, 5, 10, 15, 20 };
  10. foreach (int i in numbers)
  11. {
  12. Console.Write(" " + i);
  13. }
  14. Console.WriteLine("\n");
  15. string[] towns = { "India", "London", "Paris", "Milan", "New York" };
  16. foreach (string town in towns)
  17. {
  18. Console.Write(" " + town);
  19. }
  20. Console.ReadKey();
  21. }
  22. }
  23. }

Output :

C Sharp Language print 'int' or 'string' values use  foreach in C Sharp language

Computer Science Engineering

Special Notes

It's a special area where you can find special questions and answers for CSE students or IT professionals. Also, In this section, we try to explain a topic in a very deep way.

CSE Notes