Foreach in C#: The Loop
Programming can seem like a daunting task, but it’s nothing that can’t be learned without a little hard work and time. There are a lot of tools out there that can help you get the hang of it. In fact, there’s even an Udemy course about programming and Learning to Create Android Apps in C#.
C# programming makes use of various types of loops in order for a programmer to make several statements automatically or to set conditions and have them play out over a specific number of times. In this particular programming language, you can use loops for practically anything. It is all based on what you want the loop to do.
One of the more complex loops in programming is the foreach loop. In other loops, such as the while loop, do while loop, etc. you set a sort of a condition and you let the program operate based on that condition, but a foreach loop does something that’s a bit different.
A foreach loop, as the name suggests, repeats a specific group of statements based on each element in a particular array or collection of objects.
These terms may seem a bit confusing to you at first, but that’s the case for any programmer. If you want to understand more about the language before you start reading about loops, check out the Udemy course C# Tutorial for Beginners.
What is a Foreach Loop Exactly?
Before, we mentioned that a foreach loop repeats statements based on the collection of elements in an array. This is called enumeration, and you will see it a lot in the programming world. A foreach is really simple to create and it has some similarities to the C# for loop.
The reason why people use foreach loops is because they help reduce the amount of error in the number of elements that are used for the loop. In programming, being off by one can completely crash the entire program in some instances, so having a loop that does everything perfectly the right number of times is incredibly useful.
Looking at the Basic Structure of a Foreach Loop
Below you will find the basic structure of a foreach loop that you will see time and time again. This is the skeleton of the loop that you will be using in your programs.
Foreach (int x in array) { Console.WriteLine(x); }
Of course, just like with any other program, the statement Console.WriteLine(x) can be anything you want. This is simply what the program will do in the instance of the loop. You can have the statement be x++ and have the x incremented by 1 or anything else you want to do to the list of numbers in the array.
This is the basic structure, and now that you see the simplest way to make a foreach loop we will explore some examples that show how this loop works and what makes it useful.
Examples of a Foreach Loop
In programming there are things known as an array. An array is a collection of terms used in programs that you can use either individually or together. You can make an array out of any data type.
Below is an example of a string of arrays.
String[] animals = { “Dog”, “Cat”, “Bird”, “Mouse”, “Fish” };
This creates an array where the values go from 0 – 4. In those values there is an animal that represents it. In the 0 slot there is a Dog, in the 1 slot there is a cat, and so on.
Now that we have set up an array we just have to create a foreach loop for it. Below is the foreach loop we will use for this array.
Foreach(string value in animals) { Console.WriteLine(value); }
When you write this string and compile the code you should get the following output:
Dog Cat Bird Mouse Fish
What the loop has done is go through each element in the string, which has been identified as value, and print them out on a line. Since there are five elements in the string, the program printed out each element and then stopped.
This is essentially everything that a foreach loop does. Let’s look at another example of a foreach loop using a different data type.
Manipulating Foreach Loops
Before we simply created a foreach loop and had it print out the list of statements in our string, but now we are going to do something a bit more complex. This foreach loop will only be dealing with integers, but we will adjust the values accordingly as well.
For starters let’s create the loop that we will be using. As always remember to create an array for your loop.
Int[] examplearray = new int[] { 0, 1, 2, 3, 3, 4, 5};
Now that the array has been created we can start working on the foreach loop.
Foreach (int element in examplearray) { Console.WriteLine(element); }
Let’s break down the code line by line and see how it works. Since this is a rather simple bit of code, it won’t be that difficult.
The first statement in the code is as follows.
Foreach (int element in examplearray)
This sets up the foreach loop and we classify the items in the example array as an element. That means every integer in our array is now known as an element.
The next line of code writes out these elements.
Console.WriteLine(elements);
That’s all there is to this program, but let’s adjust it a bit and see some of the other basic functions of this loop.
Changing the Code
Keep the same array, but instead of writing the foreach loop from above we will write another one.
Int count = 0; Foreach (int element in examplearray) { Count += 1; Console.WriteLine(“Element #{0}: {1}”, count, element); } Console.WriteLine("Number of elements in the array: {0}", count);
The output of this code is a bit different. Notice how it prints out the elements and then counts them. You should get the following output for your code.
Element #1: 0 Element #2: 1 Element #3: 2 Element #4: 3 Element #5: 3 Element #6: 4 Element #7: 5 Number of elements in the array: 7
Now what if we were to do change one line of code where the count was +=2 instead of += 1?
If that were to happen, then the output of the program would be 0, 2, 3, 5 and the code would say that the number of elements in the array were only 4 and not 7.
Also notice that if you were to change the count so that it started at 1 and not at 0 then the first element would be skipped.
It’s important to note that computers start counting at 0 and not at 1 as people commonly do. The first element in an array is the 0 element, and the second is the first element, so on and so on. There are small things like this that can be easily overlooked and make programming a lot more difficult.
Learning C# Programming
This is just one type of loop in programming, but there are several others. If you want to really get the hang of programming, your best bet is to learn them all. There are several resources out there to help you. Check out the courses C# Tutorial for Beginners and Exploring the Fundamentals of C# to help get started.
Recommended Articles
Top courses in C# (programming language)
C# (programming language) students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.