Looping in Arrays

Arrays are the sequence of data stored in order to give direct access to any data by knowing it’s index value or the position of that data in an array. The problem of storing a list of student names or a list of some important integers can be solved using an array.

Arrays can be one-dimensional or multi-dimensional. We will understand this using this example.

using System;
namespace forArrays { 
    class Program { 
        static void Main(string[] args) { 
            int[] n = new int[5] { 54,45,21,62,34 }; 
            int max = 0; 
            Console.Write("Given array is:- "); 
            for(int i=0; i<5; i++) { 
                Console.Write(n[i]+", "); 
                if (n[i] > max) max = n[i]; 
            } 
            Console.Write("\nThe maximum element in the array is "+max); 
            Console.ReadLine(); 
        } 
    } 
}

 

In this program, we are finding the peak element in the array. Let’s break the code. In line 5 we are declaring an integer array of length 5 and since in c# array indexing starts from 0, so we will have five positions indexed as 0, 1, 2, 3, 4. These indexes hold the values given in the curly braces respectively. We can also initialize an array without providing the values. e.g-int[] n = new int[5];
Now in line 8 to 11, there is a for loop running. Well, loops are a handy tool which prevents us from writing redundant code. The syntax of for loop goes like this.for(initialize; condition; increament){} There are other loop structures available such as while and do while. We can also create a nested loop using one loop inside another. Thus in line 8 to 11 we are calculating the maximum value and printing the array.
The output of the program gives this.

In this example we used one-dimensional array, like this we can use 2D array for representing matrices. It can be initialised using the syntax. int[,]n = new int[4, 5] This initialises a 2D array with 4 rows and 5 columns. Like this, we can have n-dimensional arrays.

Leave a Reply

Your email address will not be published. Required fields are marked *