- Back to Home »
- C#.NET »
- C#.NET foreach loop
Posted by :
Sudhir Chekuri
Thursday, 31 December 2015
foreach loop is a special loop used for collections and arrays. It is repeated based on the number of elements in a collection. It automatically takes one by one element from a collection and it is repeated till the last element is printed.
Syntax for C# foreach loop
foreach(type variable in collect:ion/array)
{
statements
}
Example program using C# foreach loop
Program
Output
7
8
9
C#.NET program to print how many times a character is present in a string
Output
3
Explanation
above program contains a string variable s which contain "arshadmohammod"
In the above string a is repeated 3 times arshadmohammod
That string is divided into an array of characters using method ToCharArray( ) . -
char[ ] c = s.ToCharArray( );
count is a variable of int type intialized with zero used to count no of a's repeated in the string.
using for each loop all elements in char array are stored into ch one by one and repeatedly checked using if condition.
if (ch == 'a')
{
count++;
}
if element matched with a then count is incremented by one.
after the foreach loop the number in count variable is printed as output.
Syntax for C# foreach loop
foreach(type variable in collect:ion/array)
{
statements
}
Example program using C# foreach loop
Program
using System;
namespace loops
{
class Program
{
static void Main(string[] args)
{
int[] i = new int[3] { 7, 8, 9 };
foreach (int a in i)
{
Console.WriteLine(a);
}
Console.ReadKey();
}
}
}
7
8
9
C#.NET program to print how many times a character is present in a string
using System;
namespace Chars
{
class Program
{
static void Main(string[] args)
{
string s = "arshadmohammod";
char[] c = s.ToCharArray();
int count = 0;
foreach (char ch in c)
{
if (ch == 'a')
{
count++;
}
}
Console.WriteLine("no of times a repeated is
:" + count);
Console.ReadKey();
}
}
}
3
Explanation
above program contains a string variable s which contain "arshadmohammod"
In the above string a is repeated 3 times arshadmohammod
That string is divided into an array of characters using method ToCharArray( ) . -
char[ ] c = s.ToCharArray( );
count is a variable of int type intialized with zero used to count no of a's repeated in the string.
using for each loop all elements in char array are stored into ch one by one and repeatedly checked using if condition.
if (ch == 'a')
{
count++;
}
if element matched with a then count is incremented by one.
after the foreach loop the number in count variable is printed as output.