Menu
Coddy logo textTech

Each Loop Type

Part of the Logic & Flow section of Coddy's C# journey — lesson 15 of 66.

C# offers several loop types, each with specific use cases.

Use a for loop when you need precise control:

// Loop from 0 to 4
for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}

Use a while loop when the number of iterations is unknown:

// Continue as long as the condition is true
int i = 0;
while (i < 5)
{
    Console.WriteLine(i);
    i++;
}

Use a do-while loop to execute at least once:

// Always executes at least once
int i = 0;
do
{
    Console.WriteLine(i);
    i++;
} while (i < 5);

Use foreach for arrays when index isn't needed:

string[] fruits = { "apple", "banana", "cherry" };
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}
challenge icon

Challenge

Medium

Create a method called findWithDifferentLoops that:

  1. Takes an array of integers and a target value as parameters
  2. Finds the index of the target value using four different loop types:
    • for loop
    • while loop
    • do-while loop
    • foreach loop (with a counter)
  3. Returns the index found by the for loop (-1 if not found) as an integer

For example, if the target value is found at index 2 using the for loop, return 2. If the target value is not found in the array, return -1.

Note: You don't need to print any results - just return the integer index value.

Cheat sheet

C# offers several loop types for different use cases:

For loop - use when you need precise control:

for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}

While loop - use when the number of iterations is unknown:

int i = 0;
while (i < 5)
{
    Console.WriteLine(i);
    i++;
}

Do-while loop - use to execute at least once:

int i = 0;
do
{
    Console.WriteLine(i);
    i++;
} while (i < 5);

Foreach loop - use for arrays when index isn't needed:

string[] fruits = { "apple", "banana", "cherry" };
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

Try it yourself

public class FindWithDifferentLoops
{
    // Implement the findWithDifferentLoops method
    public static int findWithDifferentLoops(int[] numbers, int target)
    {
        // Write your code here
        
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow