Search⌘ K
AI Features

Arrays with Loops

Explore array handling in C# using loops like for, foreach, and while. Understand indexing, array length, and dynamic array creation. Practice real problems such as generating Fibonacci sequences, testing palindromes, and sorting arrays to strengthen your programming skills.

The for loop with arrays

The individual values in an array are accessed through an index number. The for loop variable can be used as an index number. However, the array values can also be used directly in a for loop.

The following program demonstrates the various ways of accessing array elements:

C#
class Test
{
static void Main()
{
string[] vals = {"-5", "C#", "3.8"};
System.Console.WriteLine("One way of printing an array: ");
for (int i = 0; i < vals.Length; i++)
{
System.Console.WriteLine(vals[i]);
}
System.Console.WriteLine("Another way of printing an array: ");
foreach (string s in vals)
{
System.Console.WriteLine(s);
}
}
}

In the code above:

  • The new item is the vals.Length function, which is used to get the length of the array.
  • The first for loop accesses the array values with the help of the loop variable, i.
  • The foreach loop directly accesses the array values.

The while loop with arrays

We usually use the while loop to deal with arrays when the number of iterations is not fixed. For example, let’s say we want to generate n terms of a Fibonacci sequence and store it in an array, where n is the user input. A Fibonacci sequence ...