Friday, October 7

Find Maximum Value using Reference-type C-sharp Language Code


The code below will allow a user to enter differnet values of float type and after that you will be shown a maximum value which is existing in array of float type. Method which is marked as maxValue is taking two arguments first is an array which has a predefined size and the next one is max value. array is of one dimensional. In maxValue method a loop structure is implemented which will start from the zero to the size of array - 1.



you can use different approaches to handle loop like getUpperBound and GetLowerBound both these built-in methods are concerned with array. one more important thing which must be coated here to avoid mis-conception. Array is a refernence type the declaration syntax of an array in c-sharp is int[] arr = new int[Size]; the first part int[] arr is a reference and the next part is to reserve a contiguous memory all will be of same size. as  you can see in the arguments of maxValue ref keywor is being used which contains a reference to its data. Passing a value-type variable to a method means passing a copy of the variable to the method. Any changes to the parameter that take place inside the method have no affect on the original data stored in the variable. If you want the called method to change the value of the parameter, you have to pass it by reference, using the ref or out keyword. you can implement this technique by passing value type there will be same output. Need is to make a concept of ref-type and value-type. An example below is to clear your concept.

/////////////////////////////////////////////////////////////////////////// Begins /////////////////////////////////////////////////////////////////////////////
namespace largest_float
{
    class Program
    {
        static float maxValue(float[] arr,ref float max)
        {
            for (int j = 0; j < arr.Length; j++)
            {
                if (max < arr[j]) //Checking the condition if it gets true then if block will be executed
                {
                    max = arr[j]; //max value is being updated
                }
            }
            return max;
        }
        static void Main(string[] args)
        {
            float[] arr = new float[5];
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = float.Parse(Console.ReadLine());
            }
            float max = arr[0]; //In ref-type value ust be initialized before passing it to any method
            max = maxValue(arr,ref max); //calling a user define method
            Console.WriteLine("Max Value: {0}", max);
            Console.ReadLine();
        }
    }
}

/////////////////////////////////////////////////////////////////////////// Ends ///////////////////////////////////////////////////////////////////////////////

No comments:

Post a Comment