Hello, Explorer! Today, we will revisit C# loops, essential tools that simplify repetitive tasks. Think of loops like a marathon of TV series episodes. We will venture into the C# looping universe and acquire hands-on experience by applying loops to collections like arrays
and strings
.
Have you ever experienced repeating a favorite song on a loop? That's what loops are all about in programming too. For example, you can print greetings for an array of friends using a for
loop:
In C#, a for
loop works with any sequence, like arrays
or strings
. Let's print greetings for an array of friends using a for
loop:
C#1using System; 2 3class Program 4{ 5 static void Main() 6 { 7 string[] friends = { "Alice", "Bob", "Charlie", "Daniel" }; 8 // The `for` loop initializes an index (`i`) and runs from 0 to the length of the array 9 for (int i = 0; i < friends.Length; i++) 10 { 11 // Access each element using the index `i` 12 Console.WriteLine($"Hello, {friends[i]}! Nice to meet you."); 13 } 14 } 15} 16/* 17Prints: 18Hello, Alice! Nice to meet you. 19Hello, Bob! Nice to meet you. 20Hello, Charlie! Nice to meet you. 21Hello, Daniel! Nice to meet you. 22*/
Each loop iteration updates the variable (i
) to the next sequence value before executing the code block. This is useful when you need the index for accessing elements in an array.
A foreach
loop is used to iterate over elements in a collection without the need for an index. It simplifies the process of accessing each element without needing to manage the loop counter manually. Here's an example:
C#1using System; 2 3class Program 4{ 5 static void Main() 6 { 7 string[] friends = { "Alice", "Bob", "Charlie", "Daniel" }; 8 // `friend` is the loop variable, taking each name in the `friends` array 9 foreach (string friend in friends) 10 { 11 // for each `friend`, this line is executed 12 Console.WriteLine($"Hello, {friend}! Nice to meet you."); 13 } 14 } 15} 16/* 17Prints: 18Hello, Alice! Nice to meet you. 19Hello, Bob! Nice to meet you. 20Hello, Charlie! Nice to meet you. 21Hello, Daniel! Nice to meet you. 22*/
The main difference between for
and foreach
loops is that for
loops are index-based, allowing you to modify the loop variable and have more control over the iteration process. Foreach
loops, on the other hand, are simpler to write but don't provide access to the index, making them more suitable for read-only iterations over collections.
While
loops execute code continuously until a condition becomes false. Here's a simple example:
C#1using System; 2 3class Program 4{ 5 static void Main() 6 { 7 int num = 0; 8 // The loop keeps running until `num` is greater than or equal to 5 9 while (num < 5) 10 { 11 Console.WriteLine(num); // prints numbers from 0 to 4 12 // increase `num` by 1 each iteration 13 num += 1; 14 } 15 } 16} 17/* 18Prints: 190 201 212 223 234 24*/
As you can see, before each iteration, C# checks the condition (num < 5
). If it's true, the code block runs; otherwise, C# exits the loop.
C# loops can directly work with collections, making it easy to handle elements of an array
or string
.
For instance, consider looping over an array:
C#1using System; 2 3class Program 4{ 5 static void Main() 6 { 7 // array of fruits 8 string[] fruits = { "apple", "banana", "cherry" }; 9 // The `for` loop initializes an index (`i`) and runs from 0 to the length of the array 10 for (int i = 0; i < fruits.Length; i++) 11 { 12 Console.WriteLine(fruits[i]); // prints each fruit using the index `i` 13 } 14 } 15} 16/* 17Prints: 18apple 19banana 20cherry 21*/
And, looping over a string:
C#1using System; 2 3class Program 4{ 5 static void Main() 6 { 7 string word = "hello"; 8 // `letter` is each individual character in the `word` 9 foreach (char letter in word) 10 { 11 Console.WriteLine(letter); // prints each letter in 'hello' 12 } 13 } 14} 15/* 16Prints: 17h 18e 19l 20l 21o 22*/
Loops are integral to programming. They are used in various programming applications, such as summing numbers in an array or parsing text.
C#1using System; 2 3class Program 4{ 5 static void Main() 6 { 7 // Array of numbers 8 int[] numbers = { 1, 2, 3, 4, 5 }; 9 int total = 0; 10 // The `for` loop initializes an index (`i`) and runs from 0 to the length of the array 11 for (int i = 0; i < numbers.Length; i++) 12 { 13 total += numbers[i]; // add each number in the array using the index `i` 14 } 15 Console.WriteLine(total); // prints the total sum 16 } 17} 18/* 19Prints: 2015 21*/
C#1using System; 2 3class Program 4{ 5 static void Main() 6 { 7 // string 8 string text = "hello"; 9 int vowel_count = 0; 10 // `letter` is each character in `text` 11 foreach (char letter in text) 12 { 13 // If a vowel letter is found, increment the count 14 if ("aeiou".Contains(letter)) 15 { 16 vowel_count += 1; 17 } 18 } 19 Console.WriteLine(vowel_count); // prints the count of vowels 20 } 21} 22/* 23Prints: 242 25*/
Well done on getting a grasp of C# loops! We brushed up on looping fundamentals, C#'s for
and while
loops, and how to loop over collections. Now, it's time for some essential practice exercises to cement your learning. The more problems you solve, the more adept you become. Onward, we continue on the programming voyage!