13 Replies - 727 Views - Last Post: 28 February 2011 - 10:22 AM Rate Topic: -----

#1 Tharkis  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 23
  • Joined: 20-October 10

How do I pass an array to a method that uses output parameters

Posted 27 February 2011 - 06:23 PM

0 down vote favorite


I have a method that has 2 output parameters. The method should take an array and return both the sum and the average of the values in the array. There is another method that creates an array from user input. The array needs to be initialized from the main method. I am really stumped with this one. I hope you guys can help. I have included my code below.
// Create a console-based application whose Main() method declares an array of eight integers.
//
// Call a method to interactivelyfill the array with any number of values up to eight.
//
// Call a second method that accepts out parameters for the arithmetic average and the sum of the values in the array.
//
// Display the array values, the number of entered elements, and their average and sum in the Main() method.


using System;

namespace ArrayManagment
{
    class Program
    {
        static void arrayMath(out int sum, out int avg)
        {
           sum = myArray.Sum();
           avg = myArray.Average();
        }
        static void displayArray(int[] myArray)
        {
            Console.Write("Your numbers are: ");
            for (int i = 0; i < 8; i++)
                Console.Write(myArray[i] + " ");
            Console.WriteLine();

        }

        static int[] fillArray()
        {
            int[] myArray;
            myArray = new int[8];
            int count = 0;
            do
            {
                Console.Write("Please enter a number to add to the array or \"x\" to stop: ");
                string consoleInput = Console.ReadLine();
                if (consoleInput == "x")
                {
                    return myArray;
                }
                else
                {
                    myArray[count] = Convert.ToInt32(consoleInput);
                    ++count;
                }

            } while (count < 8);

            return myArray;

        }

        static void Main(string[] args)
        {
            int[] myArray;
            myArray = new int[8];
            myArray = fillArray();
            int sum, avg;
            arrayMath(out sum, out avg);

            displayArray(myArray);


        }
    }
}



Is This A Good Question/Topic? 0
  • +

Replies To: How do I pass an array to a method that uses output parameters

#2 kevin_mchugh  Icon User is offline

  • D.I.C Head

Reputation: 11
  • View blog
  • Posts: 70
  • Joined: 08-April 09

Re: How do I pass an array to a method that uses output parameters

Posted 27 February 2011 - 06:56 PM

Hello,

Ok I am going to reply, hopefully without getting mocked by smarter people around here, but it looks to me like you need to have a look at firstly scope, then parameter passing as this program shouldn't work at all.

Maybe I am wrong, and if I am then please feel free to flame me, but if not.... it could be helpful.

Basically when you write a method it should be public/private etc. the type of object it will return (void if it returns nothing) then the name of the the method then the input parameters it expects.

So lets say


public string whatAmI(String name)
{
  return name + "is a douche bag!";
}



This should return a string which says "Kevin is a a douche bag!"

Also if you create a variable inside a function, even if its in main, no other function can see it. But if you go back to the top of your class, outside any of the functions and create global variables all of the functions in that class should be able to accsess them, as follows:


private int age;

public void setAge(int a)
{
 this.age = a;
}

public String getAge()
{
 return this.age;
}




I hope that is of some help. I realise I haven't answered your specific problem but "Give a man a fish and he will eat for a day. Teach him to fish and...." well you get the idea.

Feel free to flame me if I am being a tool btw.

Kev
Was This Post Helpful? 1
  • +
  • -

#3 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 992
  • View blog
  • Posts: 972
  • Joined: 30-September 10

Re: How do I pass an array to a method that uses output parameters

Posted 28 February 2011 - 02:28 AM

Hi,

Okay, the first thing you have to realise is the difference (or, at least, what I consider to be the difference ;)) between declaration and initialisation.

This is declaration of an int array:

int[] myArray;



This is initialisation of the array that was declared above:

myArray = fillArray();



The point of outlining that is that if your assignment says initialise an array of integers in Main(). You can do something like this:


int[] myArray; //declare array here

static void Main(string[] args)
        {
            //but initialise it from within Main() 
            myArray = new int[8]; 
            myArray = fillArray();

        }




That way, 'myArray' has global scope throughout the class, and thus can be used in your arrayMath() method, as it is declared outside Main(). Just have a read of the assignment problem again and make sure you have acknowledged exactly what they are asking.

If they do want you to declare the array from within Main(), that array will scoped to Main() and so won't be available anywhere else in the program, as you know.

One way that you could 'pass' the array to the arrayMath() method is to make arrayMath() an extension method on the int[] type. You could then call arrayMath() from within Main() like this:

myArray.arrayMath(out sum, out avg);



Extension methods are 'extensions' to the type. Therefore, scope is somewhat irrelevant in this context, as the method itself has becomepart ofthe type. So, you just call it on the type as above, and 'myArray' is automatically available inside the arrayMath() method, without having to pass it in directly.

Extension Methods

This post has been edited by CodingSup3rnatur@l-360: 28 February 2011 - 03:31 AM

Was This Post Helpful? 0
  • +
  • -

#4 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 992
  • View blog
  • Posts: 972
  • Joined: 30-September 10

Re: How do I pass an array to a method that uses output parameters

Posted 28 February 2011 - 02:52 AM

View Postkevin_mchugh, on 28 February 2011 - 01:56 AM, said:

Hello,

Ok I am going to reply, hopefully without getting mocked by smarter people around here, but it looks to me like you need to have a look at firstly scope, then parameter passing as this program shouldn't work at all

...


Hi Kevin,

You are exactly right in normal circumstances, and scope of the array is exactly the problem the OP is having I think.

In this case though, the fact that he has used the 'out' keyword with his paramters and arguements in the arrayMath() method means the values of the passed in parameters (and thus the values of 'sum', and 'avg' inside the method) are available outside of his method (in the 'sum' and 'avg' variables in Main() specifically), in addition to inside the method.

Out and Ref Parameters

This post has been edited by CodingSup3rnatur@l-360: 28 February 2011 - 03:00 AM

Was This Post Helpful? 0
  • +
  • -

#5 marinus  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 135
  • View blog
  • Posts: 575
  • Joined: 14-April 10

Re: How do I pass an array to a method that uses output parameters

Posted 28 February 2011 - 03:09 AM

View Postkevin_mchugh, on 27 February 2011 - 06:56 PM, said:


private int age;

public void setAge(int a)
{
 this.age = a;
}

public String getAge()
{
 return this.age;
}



Hey Kevin , why didn't you use the getter and setter??

 private int _Qty;
 public int Qty
        {
            get { return _Qty; }
            set { _Qty = value; }

        }

Was This Post Helpful? 0
  • +
  • -

#6 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 992
  • View blog
  • Posts: 972
  • Joined: 30-September 10

Re: How do I pass an array to a method that uses output parameters

Posted 28 February 2011 - 03:19 AM

Hi Marinus,

He was giving an example of variable scope inside a method. Granted he could have still done that (in a sense) in a property... It was more appropriate and useful to the OP I think to use a method in this case though :).

This post has been edited by CodingSup3rnatur@l-360: 28 February 2011 - 03:22 AM

Was This Post Helpful? 1
  • +
  • -

#7 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5632
  • View blog
  • Posts: 12,078
  • Joined: 02-June 10

Re: How do I pass an array to a method that uses output parameters

Posted 28 February 2011 - 04:32 AM

I guess I'm missing why everyone has gone so complicated on this.
Is it just me or did this thread go sideways from the actual question asked?

Quote

Q: How do I pass an array to a method that uses output parameters

A: Just as you would any parameter

You do have to use a double not an int for average though.

I tested this and works just fine.

        static void arrayMath(int[] myArray, out int sum, out double avg)
        {
           sum = myArray.Sum();
           avg = myArray.Average();// result is double not int
        }
        static void displayArray(int[] myArray)
        {
            Console.Write("Your numbers are: ");
            for (int i = 0; i < 8; i++)
                Console.Write(myArray[i] + " ");
            Console.WriteLine();


        }

        static int[] fillArray()
        {
            int[] myArray;
            myArray = new int[8];
            int count = 0;
            do
            {
                Console.Write("Please enter a number to add to the array or \"x\" to stop: ");
                string consoleInput = Console.ReadLine();
                if (consoleInput == "x")
                {
                    return myArray;
                }
                else
                {
                    myArray[count] = Convert.ToInt32(consoleInput);
                    ++count;
                }

            } while (count < 8);

            return myArray;

        }

        private void button3_Click(object sender, System.EventArgs e)
        {
            int[] myArray;
            myArray = new int[8]{1,2,3,4,5,6,7,8};
            int sum;
            double avg;
            arrayMath(myArray, out sum, out avg);

            displayArray(myArray);
            Console.WriteLine("Average: " + avg);
            Console.WriteLine("Sum: " + sum);
        }


Was This Post Helpful? 1
  • +
  • -

#8 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 992
  • View blog
  • Posts: 972
  • Joined: 30-September 10

Re: How do I pass an array to a method that uses output parameters

Posted 28 February 2011 - 04:47 AM

@tlhIn`toq

You could be right. I took the OP as meaning arrayMath() has to take the two out parameters only. He has passed the array to fillArray(), so I assume he knows how to pass the array to the method. That's probably where I my mistake is...I shouldn't assume anything :)

EDIT: You were correct:

http://stackoverflow...tput-parameters

:facepalm:

This post has been edited by CodingSup3rnatur@l-360: 28 February 2011 - 07:51 AM

Was This Post Helpful? 0
  • +
  • -

#9 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4559
  • View blog
  • Posts: 7,980
  • Joined: 08-June 10

Re: How do I pass an array to a method that uses output parameters

Posted 28 February 2011 - 08:48 AM

Quote

0 down vote favorite


When you see a post start with that, first check stack overflow for the exact same title. It means they copied and pasted their exact question.
Was This Post Helpful? 1
  • +
  • -

#10 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5632
  • View blog
  • Posts: 12,078
  • Joined: 02-June 10

Re: How do I pass an array to a method that uses output parameters

Posted 28 February 2011 - 08:57 AM

View PostinsertAlias, on 28 February 2011 - 09:48 AM, said:

Quote

0 down vote favorite


When you see a post start with that, first check stack overflow for the exact same title. It means they copied and pasted their exact question.


Which is exactly what he did:
http://stackoverflow...tput-parameters

And got the same answer I gave: You use it like any other parameter.

Only the OP was nice enough to thank the people over at StackOverflow.

This might seem petty, but I don't like wasting my time or being used as a source to double check the answers that another forum provided. I think tharkis just got added to my "dont-bother-to-help.txt" list. There are too many other people asking for help here to be used as a redundant resource.

This post has been edited by tlhIn`toq: 28 February 2011 - 09:02 AM

Was This Post Helpful? 0
  • +
  • -

#11 Tharkis  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 23
  • Joined: 20-October 10

Re: How do I pass an array to a method that uses output parameters

Posted 28 February 2011 - 09:24 AM

View PosttlhIn`toq, on 28 February 2011 - 08:57 AM, said:

View PostinsertAlias, on 28 February 2011 - 09:48 AM, said:

Quote

0 down vote favorite


When you see a post start with that, first check stack overflow for the exact same title. It means they copied and pasted their exact question.


Which is exactly what he did:
http://stackoverflow...tput-parameters

And got the same answer I gave: You use it like any other parameter.

Only the OP was nice enough to thank the people over at StackOverflow.

This might seem petty, but I don't like wasting my time or being used as a source to double check the answers that another forum provided. I think tharkis just got added to my "dont-bother-to-help.txt" list. There are too many other people asking for help here to be used as a redundant resource.



Actually since no one responded to this right away, and the nice people at StackOverflow did, I thanked them as soon as I got the answer. You however, replied while I was sleeping this morning. Long after I had the answer. I posted it to both forums, not because I wanted to verify the answer. I posted it both places because I needed a quick answer. However, I fail to follow your logic in checking an answer. This is the internet, not everything people say on the internet is true. I see no problem with checking your facts. As I said it was the fact that I needed the answer quickly that prompted me to post in both places.

While I appreciate everyone's comments, I don't appreciate you being dickish about my percieved lack of response to your answer. Especially when your answer, though it was exactly what I was looking for, was 10 hours late to the party. To tell you the truth, the only reason why I even responded this soon was to tell you that yes, you are being petty.

I would like to point out that this, will be my last post on this forum. Mostly because I think posters like tlhIn`toq speak worlds about your forum. Good luck and happy coding to everyone else. tlhIn`toq, you can pound sand. Oh, and I gave you the up vote you apparently needed to satisfy your ego.

This post has been edited by Tharkis: 28 February 2011 - 09:28 AM

Was This Post Helpful? 0
  • +
  • -

#12 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5632
  • View blog
  • Posts: 12,078
  • Joined: 02-June 10

Re: How do I pass an array to a method that uses output parameters

Posted 28 February 2011 - 09:47 AM

Somehow to me the logic just doesn't hold up.

It was posted on StackOverflow because an immediate answer was needed.
But then it was posted here as a copy/paste from S.O.: Doesn't that mean they didn't answer right away? Did I miss something in that logic?

And wouldn't the fastest solution be to just treat it like any other parameter? Generally speaking trying is a lot faster than typing a question and waiting for someone to reply. I mean I only ask questions after I've tried and tried then nothing worked. I'd get it of there was some cryptic syntax for parameters that only applies when there is an 'out' reference.

But wouldn't common sense be to try it like any other or along the same syntax as other C# uses, then when that failed look it up on MSDN, then when that failed Google like hell, then when that failed ask a forum.

Now I'm just curious. I've already been told that I'm a prick for not wanting to have my time wasted. Okay. I'm good with that.

But since this thread is going... What is the normal process for the rest of you when trying to solve/find a solution? Maybe I'm just really the odd man out here but I do this:
  • try it like any other or along the same syntax as other C# uses,
  • then when that failed look it up on MSDN,
  • then when that failed Google like hell,
  • then when that failed ask a forum.

Was This Post Helpful? 0
  • +
  • -

#13 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4559
  • View blog
  • Posts: 7,980
  • Joined: 08-June 10

Re: How do I pass an array to a method that uses output parameters

Posted 28 February 2011 - 09:49 AM

Ok, this thread is no longer productive.
Was This Post Helpful? 0
  • +
  • -

#14 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6092
  • View blog
  • Posts: 23,612
  • Joined: 23-August 08

Re: How do I pass an array to a method that uses output parameters

Posted 28 February 2011 - 10:22 AM

View PostTharkis, on 28 February 2011 - 11:24 AM, said:

Actually since no one responded to this right away, and the nice people at StackOverflow did, I thanked them as soon as I got the answer. You however, replied while I was sleeping this morning. Long after I had the answer. I posted it to both forums, not because I wanted to verify the answer. I posted it both places because I needed a quick answer. However, I fail to follow your logic in checking an answer. This is the internet, not everything people say on the internet is true. I see no problem with checking your facts. As I said it was the fact that I needed the answer quickly that prompted me to post in both places.


A half an hour is too long for you to wait? Pffft. This ain't a chat room, dude.

This post has been edited by JackOfAllTrades: 28 February 2011 - 10:22 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1