In this tutorial, we’ ll learn How to access array elements using loops (for, while, foreach, do-while) in C#.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
class GFG { // Main Method public static void Main() { // declares an Array of integers. int[] intArray; // allocating memory for 5 integers. intArray = new int[5]; // initialize the first elements // of the array intArray[0] = 10; // initialize the second elements // of the array intArray[1] = 20; // so on... intArray[2] = 30; intArray[3] = 40; intArray[4] = 50; // accessing the elements // using for loop Console.Write("For loop :"); for (int i = 0; i < intArray.Length; i++) Console.Write(" " + intArray[i]); Console.WriteLine(""); Console.Write("For-each loop :"); // using for-each loop foreach(int i in intArray) Console.Write(" " + i); Console.WriteLine(""); Console.Write("while loop :"); // using while loop int j = 0; while (j < intArray.Length) { Console.Write(" " + intArray[j]); j++; } Console.WriteLine(""); Console.Write("Do-while loop :"); // using do-while loop int k = 0; do { Console.Write(" " + intArray[k]); k++; } while (k < intArray.Length); } } |
Output: