Arrays with Loops
Explore how to use loops to access and manipulate array elements in C#. Understand indexed and direct access with for and foreach loops. Practice creating Fibonacci sequences using while loops and solve problems like sorting arrays and palindrome checks to strengthen your C# array handling 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:
In the code above:
- The new item is the
vals.Lengthfunction, which is used to get the length of the array. - The first
forloop accesses the array values with the help of the loop variable,i. - The
foreachloop 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 is a sequence in which each number is the sum of the two preceding ones, except the first two terms.
Let’s start by noting a few terms in this sequence: ...