Menu
Coddy logo textTech

Loop Through

Lesson 10 of 14 in Coddy's Strings and Arrays in C# course.

You can loop through the array elements with the for loop and use the length property to specify how many times the loop should run.

double[] coolNums = {3.14, 1.69, 9.99};
for (int i = 0; i < coolNums.Length; i++) {
	Console.WriteLine(coolNums[i]);
}

The above prints all the numbers in the array!

There is also a shorter form for an array called a "for-each" loop:

double[] coolNums = {3.14, 1.69, 9.99};
foreach (double num in coolNums) {
	Console.WriteLine(num);
}

The full format is:

foreach (type variableName in arrayName) {
	// loop body
}
challenge icon

Challenge

Easy

Write a function named onlyOdd that gets an array of integers as an argument and prints only the odd numbers.

Try it yourself

using System;

class OnlyOdd {
    public static void onlyOdd(int[] nums) {
        // Write code here
    }
}

All lessons in Strings and Arrays in C#