0

I am trying to write a C# function to determine the maximum value in an array and to pass it by reference.

It is my first time programming in C#, but it's really bugging me that I don't to seem to be able to assign it correctly in the main.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication4
{
    class Program
    {
        static void Maxim(int n, ref int maxim, params int[] v) {
            int i,  max=v[0];

            for (i = 0; i < n; i++) {
                if (v[i] >  max)  max = v[i];
            }
        }

        static void Main()
        {
            int[] vector = new int[10];
            int n, i;
            int maximul;

            Console.WriteLine("Introduceti numarul de elemente: ");
            n = Int32.Parse(Console.ReadLine());

            Console.WriteLine("Valoarea introdusa: {0}", n);
            for (i = 0; i < n; i++) {
                vector[i] = Int32.Parse(Console.ReadLine());
            }

            Console.WriteLine("Elementele introduse sunt: ");
            for (i = 0; i < n; i++) {
                Console.WriteLine("Elementul {0}:  {1}", i + 1, vector[i]);
            }

            Maxim(n, ref maximul, vector);

            Console.WriteLine("Maximul din vector: {0}",  maximul);
            Console.ReadLine();
        }
    }
}

It returns me the following error: Use of unassigned local variable.

cdbitesky
  • 1,390
  • 1
  • 13
  • 30
radu-matei
  • 3,469
  • 1
  • 29
  • 47

3 Answers3

3

Initialize your variables when you defining them :

int n = 0, i = 0;
int maximul = 0;

Probably the reason is you are passing maximul as ref parameter but you didn't initialize it.

From documentation:

An argument that is passed to a ref parameter must be initialized before it is passed. This differs from out parameters, whose arguments do not have to be explicitly initialized before they are passed.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • You don't need use ref in your code. Just pass value is fine. And maximul was not used at all. –  Feb 09 '14 at 01:27
0

Maxim is a redundant variable. You're never using it in your function.

TGH
  • 38,769
  • 12
  • 102
  • 135
0

The problem is that the maximum value is being stored in the local max but the caller is expecting it to be written into the ref parameter maxim. If you delete the local max and use maxim instead this will fix the problem.

A more idiomatic way to write this function is to not use ref parameters at all. Instead just return the value directly

static intMaxim(int n, params int[] v) {
  int i,  max=v[0];
  for (i = 0; i < n; i++) {
    if (v[i] >  max)  max = v[i];
  }
  return max;
}

Note that the n parameter is also not truly needed here. The length of the array v can be accessed via the expression v.Length

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454