Continue for Loop Within Other Loop
Most of the time, our C# loops process a collection or count from one value to the next. But sometimes we have to do complex calculations or handle nested collections. In those cases we need the more advanced nested loops. Let's see how those work.
IN THIS ARTICLE:
# Understand nested loops in C#
A nested loop is a construction of two or more loops that are placed inside each other (Liberty & MacDonald, 2009; Sempf, Sphar, & Davis, 2010). This makes elaborate calculations possible, as well as looping through nested arrays, lists, and dictionaries.
With a nested loop, the inner loop runs to completion for each iteration of the outer loop (Liberty & MacDonald, 2009; Sempf et al., 2010). This behaviour adds an extra dimension to our loop. Now instead of simply going through a list's length, we can also loop through its depth.
To clarify, the inner and outer loop terms refer to different parts of a nested loop:
Sometimes when we have a lot of loops inside each other, the first loop is called the outermost loop. And the most deeply embedded one the innermost loop.
# Quick example: nested for
loop in C#
Here's a quick nested loop example:
int rows = 2 , columns = 4 ; // Make a rectangular array int [,] recArray = new int [ rows , columns ]; // Loop over each row and column for ( int i = 0 ; i < rows ; i ++) { for ( int j = 0 ; j < columns ; j ++) { recArray [ i , j ] = i + j ; } }
Here we have a nested for
loop. The outer for
loop goes from 0
up to 2
(the value of the rows
variable). For each of those loop cycles, the inner loop goes from 0
to (but not including) 4
(columns
). This fills a 2x4 array. That is, each cycle of the outer loop creates a row, and inner loop then fills the columns of that row.
Note that outer loops cannot access the loop variables of inner loops. In our example above, the outer loop – which uses the i
variable – cannot look up the j
variable. The other way around does work: the inner loop can access the outer loop's i
variable.
Now that we know what nested loops are, let's look at some more C# examples.
# Code a foreach
nested loop in C#
A foreach
loop easily loops through all values that a collection has. With this loop we don't handle loop indexes, and neither have to update the loop variable.
The default pattern of a nested foreach
loop is:
foreach ( var collection in nestedCollections ) // Outer loop { // Code that should run for each collection foreach ( var item in collection ) // Inner loop { // Code that should run for each item } }
There are two foreach
loops here. The outer loop goes through each collection in our list of nested collection (nestedCollections
). During each of those loop cycles, the collection
variable refers to a single one of those nested collections.
The inner foreach
loop then processes each item for every collection in that nested collection. That handle each single item that nestedCollections
has.
We can use the same pattern to run through two separate collections. That way for each loop cycle of the first collection, we process another collection in its entirety. This is how we for instance match the value of one list with the value in another list:
foreach ( var itemA in mainCollection ) // Outer loop { // Code that should run for each item in the main collection foreach ( var itemB in otherCollection ) // Inner loop { // Code that can compare every single // `itemA` value against all values in `otherCollection` } }
# Example: code a nested foreach
loop in C#
The program below shows how a nested foreach
loop works in practice. The program first goes through a list of domain extensions (like .net
and .com
). An inner loop then matches each extension against a domain name. The result is a table with domain extensions and example domains.
The program's full code is:
using System ; class Kodify_Example { static void Main () { string [] extensions = { ".com" , ".org" , ".net" }; string [] domains = { "github.com" , "twitter.com" , "bitbucket.org" , "signal.org" , "windows.net" , "ghacks.net" }; // Loop through all extensions foreach ( string extension in extensions ) { Console . Write ( "{0} | \t" , extension ); // Print domains that match the web extension foreach ( string domain in domains ) { if ( domain . EndsWith ( extension )) { Console . Write ( domain + "\t" ); } } Console . Write ( "\n" ); } } }
The Main()
method we make two arrays with string values. The first, extensions
, has three different top-level domain names. The other, domains
, contains 6 example websites.
Then we make a nested loop. The outer foreach
loop goes through the extensions
array. With the extension
loop variable we fetch a single element from that array with each pass through the loop.
Inside this loop we first print the domain extension with the Console.Write()
method. Then we make a second, nested loop. This foreach
loop goes through each domain in the domains
array. The loop's domain
string variable represents one website domain.
Because our nested loop goes through all websites for each domain extension, we can match a particular top-level domain (like .net
) with an example website (windows.net
). That's exactly what the if statement does inside the inner loop.
There we check if the domain we loop over (domain
) ends with (EndsWith()
) the top-level domain extension (the outer loop's extension
variable). When it does, the if statement's code outputs that domain with Console.Write()
.
Here's how that generated output looks:
.com | github.com twitter.com .org | bitbucket.org signal.org .net | windows.net ghacks.net
# Creating nested loops with C#'s for
loop
A for
loop easily counts from one value to another. This way we loop over collections (like arrays and lists) and perform calculations. With for
loops inside each other, even more program behaviour is possible.
Here's how nested for
loops look like:
for ( int i = 0 ; i < 10 ; i ++) // Outer loop { // Code here executes once // for each outer loop cycle for ( int j = 0 ; j < 10 ; j ++) // Inner loop { // The inner loop runs to completion // for each loop cycle of the outer loop } }
The outer for
loop has the i
variable go from 0 to 10. During each of those loop cycles we run another for
loop. This one has a j
variable that also goes from 0 up to 10. For each cycle of the outer loop, the inner loop repeats 10 times.
# Example: program a nested for
loop in C#
Let's see how a nested for
loop works in practice. The console application below has a nested loop go through two arrays. One contains domain extensions (like .com
). The other has domain names (github.com
). Inside the loop we match each extension with its domain names.
The program's code is:
using System ; class Kodify_Example { static void Main () { string [] extensions = { ".com" , ".org" , ".net" }; string [] websites = { "github.com" , "twitter.com" , "bitbucket.org" , "signal.org" , "windows.net" , "ghacks.net" }; // Go through all extensions for ( int i = 0 ; i < extensions . Length ; i ++) { Console . Write ( "{0} | \t" , extensions [ i ]); // And print those domains that match the extension for ( int j = 0 ; j < websites . Length ; j ++) { if ( websites [ j ]. EndsWith ( extensions [ i ])) { Console . Write ( websites [ j ] + "\t" ); } } Console . Write ( "\n" ); } } }
We make two arrays in Main()
. The first, extensions
, has three domain name extensions. The other, websites
, has six domain names.
To process those values we make a nested loop. The outer loop is a for
loop that iterates from 0
until the number of elements in our first array (extensions.Length
). After each loop cycle we increase that i
loop variable with one (i++
). Inside this loop the Console.Write()
method outputs the current domain extension.
There we also make another for
loop. This inner loop goes through each element in the websites
array. For that we make the j
variable, and continue for as long as that variable is less than the array's length (websites.Length
). After each loop cycle we increase that variable with one (j++
).
That inner loop has an if statement. This checks if the current website we loop over (websites[j]
) ends with (EndsWith()
) the domain extension that the outer loop iterates over (extensions[i]
). When that's the case, we print the current website with Console.Write()
. This way we match the domain names and their extension.
Here's how that output looks:
.com | github.com twitter.com .org | bitbucket.org signal.org .net | windows.net ghacks.net
# Make nested loops with C#'s while
loop
With a while
loop we repeat code as long as a condition remains true
. We can also translate that behaviour to nested loops. That way we can handle data and advanced calculations.
Here's how a nested while
loop can look:
while ( conditionA ) { // Code here executes for each outer loop cycle while ( conditionB ) { // The inner loop's code runs till // completion for each outer loop cycle conditionB = ... } // Change loop condition at some point conditionA = ... }
The outer while
loop goes on for as long as conditionA
tests true
. Each time it does, the loop's code executes. There we have another while
loop. That inner loop runs based on conditionB
.
When that condition is true
, the inner loop executes. When it becomes false
, the inner loop ends and the outer loop continues. Then with the next outer loop cycle the inner loop starts again.
# Example: make a nested loop with the while
loop
The example program below has a nested while
loop process two arrays. The first contains domain extensions. The second has domain names. The program's goal is to match domain extensions (like .org
) with website domains (bitbucket.org
).
The code of this console application is:
using System ; class Kodify_Example { static void Main () { string [] extensions = { ".com" , ".org" , ".net" }; string [] websites = { "github.com" , "twitter.com" , "bitbucket.org" , "signal.org" , "windows.net" , "ghacks.net" }; int i = 0 ; // Match website extensions with their domain names // Loop through the domain extensions while ( i < extensions . Length ) { Console . Write ( "{0} | \t" , extensions [ i ]); // Then only print those domains with a matching extension int j = 0 ; while ( j < websites . Length ) { if ( websites [ j ]. EndsWith ( extensions [ i ])) { Console . Write ( websites [ j ] + "\t" ); } j ++; } Console . Write ( "\n" ); i ++; } } }
In Main()
we first make two string arrays. The first, extensions
, has top-level domain extensions. The other, websites
, has domains for technology-related websites.
Then we declare and initialise the i
variable. We use this one to control the outer loop. That while
loop is what we make next. We have that loop continue for as long as i
is less than (<
) the length of the extensions
array. That processes each of the three domain extensions.
Inside the loop we first output the top-level domain with Console.Write()
. Then we look for websites that match that domain extension.
For that we first declare the j
variable. With this variable we control the nested while
loop, which we make next. This loop runs when that variable is less than the length of the websites array (websites.Length
). For each outer loop cycle (the domain extension), this inner loop (with websites names) runs to completion.
The inner loop has an if statement. This one sees if the website we loop over (websites[j]
) ends with (EndsWith()
) the same domain extension as the outer loop's variable (extensions[i]
). When the current website indeed matches that domain, code inside the if statement outputs the website with the Console.Write()
method. This way we match the domain extension output with the example websites.
After the if statement we're still inside the inner loop. There we increase the j
variable with one (j++
). That makes the inner loop go through all array elements.
When the inner loop finishes, there are two statements left in the outer loop. We first have Console.Write()
make a new line ("\n"
). That ensures a proper output of all values. Then we increase the i
loop variable with one (i++
). That way the outer loop goes through all website extensions.
This is what the above example program outputs:
.com | github.com twitter.com .org | bitbucket.org signal.org .net | windows.net ghacks.net
# Summary
Regular loops can handle a lot of situations. But with multiple collections, complex calculations, or nested collections, we need a nested loop.
A nested loop are one or more loops placed inside each other. That way the inner loop runs to completion for each loop cycle of the outer loop.
We can make a nested loop with loops of the same kind (like two for
loops) or use different types. The most common are, however, two for
or two foreach
loops inside each other.
References
Liberty, J., & MacDonald, B. (2009). Learning C# 3.0: Master the Fundamentals of C# 3.0. Sebastopol, CA: O'Reilly Media.
Sempf, B., Sphar, C., & Davis, S.R. (2010). C# 2010 All-In-One for Dummies. Hoboken, NJ: John Wiley & Sons.
Published .
« All C# looping articles
longeneckerdinar1997.blogspot.com
Source: https://kodify.net/csharp/loop/nested-loop/
Postar um comentário for "Continue for Loop Within Other Loop"