Reputation: 77
I am very new to c# and I am trying to get my head around functions/methods.
Below, i am trying to create a program that has one function create 200 random numbers and store them in an array, i would then like another function to sort through said array and tally up duplicates. that is where the problem comes in, i am not entirely sure how to get the array from the first function or at least the values from it into the second function. the code below may be sloppy as i was kind of half way through when i got stuck.
class Program
{
static void Main(string[] args)
{
ExamineArray();
Console.ReadKey();
}
static void CreateArray(int i)
{
int[] array = new int[200];
Random rand = new Random();
for (i = 0; i<200; i++)
{
int x = rand.Next(0, 11);
array[i] = x;
}
}
static void ExamineArray()
{
for (int i = 0; i < 200; i++)
{
Console.WriteLine(CreateArray(i));
}
}
}
i have thought about having the second array go through and completely rewrite the contents of the first array but i still don't know how to get the contents over. sorry for asking such a simple question.
Upvotes: 1
Views: 65
Reputation: 23732
A method can be void, which means that it does not have a return type, or it can return an object. Usually a method that is called CreateArray
can be expected also to return that array. You have to modify the signature of your method like this:
static int[] CreateArray(int i){ // your method code goes in here}
that means it will return an array of integer. Inside the method when you have finished constructing your array use the return
keyword to get it out:
static int[] CreateArray(int numberOfArrayItems)
{
int[] array = new int[numberOfArrayItems];
Random rand = new Random();
for (int i = 0; i<numberOfArrayItems; i++)
{
int x = rand.Next(0, 11);
array[i] = x;
}
return array; // <-- here you return the array
}
Now at the calling site of this method you can now simply harvest the constructed array for example:
static void ExamineArray()
{
int[] array = CreateArray(200);
// do what ever you want with it
}
If you want to read up on method signature and return types here is the documentation and here is a tutorial
Upvotes: 3