0

Getting an error at (private int >>>TotArray<< (int[,] array)) Which tells me I cannot return value. Can anyone help me and tell me what I am doing wrong?

What this code does is it supposed to add all the numbers of this 2 dimensional array. But in the moment it does nothing.

    int[,] A = new int[3, 4] 
    { 
        { 4, -5, 12, -2},
        { -9, 15, 19, 6},
        { 18, -33, -1, 7}
    };
    public Form1()
    {
        InitializeComponent();
    }
    private int TotArray(int[,] array)//<<<<<< error
    {
        int sum = 0;
        int rows = array.GetLength(0);
        int cols = array.GetLength(1);

        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                sum += array[i, j];
            }
        }
        richTextBox1.Text = ("The sum of the array is " + sum.ToString() + ".");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        TotArray(A);
    }

3 Answers 3

2

I think you are getting an error because your TotArray method isn't actually returning an int.

What happens if you switch it to the following:

private void TotArray(int[,] array) 

And if that doesnt fix it, can you post the error message?

Sign up to request clarification or add additional context in comments.

Comments

2

Your return type is int but you are not returning anything from your method.If you don't want to return anything change return type to void or return something.

private int TotArray(int[,] array)
{
    int sum = 0;
    int rows = array.GetLength(0);
    int cols = array.GetLength(1);

    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            sum += array[i, j];
        }
    }

    return sum;
}

private void button1_Click(object sender, EventArgs e)
{
   int sum = TotArray(A);
   richTextBox1.Text = string.Format("The sum of the array is {0}.", sum);
}

4 Comments

But if I return sum it doesnt do anything... doesnt give me any values no nothing
@TheBoringGuy I'm guessing, you are not storing the returning value into a variable.If you don't store it that means you are simply ignoring it.
nvm I found the mistake I had to change private int to private void
Prefer this answer as it shows better separation of concerns. i.e. a method that totals an array only returns a total instead of also updating the value of a textbox.
0

Put

return sum;

At the end of you're TotArray method.

Then place(for testing)

Debug.WriteLine(TotArray(A));

In your calling code, run the program, check the output window and your sum should be returned in the output window.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.