Jump to content

C# arrays/lists in method parameters & returning arrays/lists from methods (confusion)

kaddle

i am at the point in the book where it is explaining the usage of arrays and lists in method parameters, as well as returning an array or list from a method. i get it for the most part, but there are some things that aren't explained in the book which are causing confusion for me. the process of using arrays and lists in the ways i will show bellow are similar, so i'll only be using array examples in this OP and translate what i learn to be used for lists as well.

 

Printing Element:

            void PrintFirstElement(int[] a)
            {
                Console.WriteLine("The first element is {0}.", a[0]);
            }
            int[] myArray = { 1, 2, 3, 4 };
            PrintFirstElement(myArray);
            Console.ReadLine();

so the code in the example above is for printing out the value of an element in whichever array is passed into the parenthesis as a parameter when calling the method (if you've been reading my programming threads from before i started learning, you could see that i've learned a lot so far ?). so i get the gist of it. the problem is that the book doesn't explain the specifics of how this process works.

 

looking at the method declaration, the parameter is (int[] a). so i can assume that the int[] part tells the method that it needs to take in the name of an integer array when the method is called. what on earth is the a character for? also, the a character is used again in the WriteLine() method, but this time it is placed before the array element. so my other question is what determines where the a character should be placed? after thinking about it i can only assume that it's a substitute for the name of the array or list, but you tell me please.

 

Returning Array:

            int[] ReturnUserInput()
            {
                int[] a = new int[3];
                for (int i = 0; i < a.Length; i++)
                {
                    Console.Write("Enter an integer: ");
                    a[i] = Convert.ToInt32(Console.ReadLine());
                    Console.WriteLine("Integer added to array.\n");
                }
                return a;
            }
            int[] myArray2 = ReturnUserInput();
            Console.ReadLine();

the code in the example above is for creating a method that makes an array based on user input. this one is a little bit more confusing than the last one. i'm definitely confused about all instances where the a character is used. someone please explain. i'm also confused about the declaration of the int i variable in the for loop and the usage of before the conversion method. how exactly does this variable translate into the elements of the array that i would use the method to declare?

Link to comment
Share on other sites

Link to post
Share on other sites

19 minutes ago, kaddle said:

what on earth is the a character for?

In this instance
 

int[] a

'a' is just the name of the variable you are creating, it is an array called 'a'. This always annoyed be when I was learning to program, most programmers name disposable variables with a single letter and I found it confusing.

Then when using

a.Length;

you are accessing the length of the array. This is a dynamic number that grows or shrinks depending on the size of the array, though it will always be one smaller than whats in the array because starting at 0.

 

for (int i = 0; i < a.Length; i++)

Whats going on with this is the 'i' is being used to tell the computer which stage of the loop it is on, so at the beginning it starts at 0. Then you have the

i < a.Length

part which is indicating that if i is less than the length of your array the loop should run again. Then

i++

just adds 1 to whatever 'i' was, so if it was 0 it becomes 1 and so on. Until it equals however long your array is then the loop stops looping.

 

Quote

how exactly does this variable translate into the elements of the array that i would use the method to declare?

I hope I've answered everything adequately for you. If I missed anything just let me know.

PS: Wait until you get into Arrays of arrays, so much fun there. Its literally mind bending but its so so good.

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, kaddle said:

what on earth is the a character for? also, the a character is used again in the WriteLine() method, but this time it is placed before the array element. so my other question is what determines where the a character should be placed? after thinking about it i can only assume that it's a substitute for the name of the array or list, but you tell me please.

You are basically correct here.

'a' is the name they chose for the array here. Of course that is a terrible name.. I get it, but that is the name they chose.

Instead of 'a' I am showing a similar situation with a different example:

private void _mainFunction()
{
	string name = "John Doe";
	string greeting = _getGreeting(name);
    Console.WriteLine(greeting);
}

private string _getGreeting(string givenName)
{
	string retval = "Hello " + givenName + ", welcome to this program!";
    
    return retval;
}

//What this looks like in a program (assuming '_mainFunction' is ran):
// Hello John Doe, welcome to this program!

In this case, parameter 'a', is switched around for 'givenName', which is a string variable, used as a variable in '_getGreeting'. It doesn't matter what the name 'givenName' was in the function that called it (_mainFunction called this function and gave variable 'name' as a parameter), this variable is only known in that particular function.

 

Substitute "givenName" for 'a' and you have a similar function as to what example you posted in your OP.

 

Small difference between passing an array/list or anything else as a parameter:

Spoiler

When you pass most variables, you're just passing its contents. When passing an array (I think a list too.. not 100% sure) you're actually passing the list.

 

If I do something like this:


void Main
{
	int someNumber = 4;
    int[] someNumbers = new int[3];
    
    // Remember, array start with index 0!
    someNumbers[0] = 5;
    
    countUp(someNumber)
    countUpArray(someNumbers)
    
    Console.WriteLine(someNumber);
    Console.WriteLine(someNumber[0]);
    
    // This will result in the program printing:
    // 4 (because I only passed along the value, so it doesn't matter I did ++ in the function).
    // 6 (because the variable started at 5, I passed along the actual array and did ++ to it, meaning the array itself got changed).
}

void countUp(int receivedNumber)
{
	number++;
}

void countUpArray(int[] receivedNumbers)
{
	// Again, arrays start at index 0!
	receivedNumbers[0]++;
}

This code gives those values, because with the function "countUp", I merely pass along the content of the int. With "countUpArray", I am actually passing the actual array. So any changes done there, are changes done to the actual array. Even though they have different names.

This is something to keep in mind, when passing an array as a parameter, you can change the contents of the array in that function.

 

Quote

the code in the example above is for creating a method that makes an array based on user input. this one is a little bit more confusing than the last one. i'm definitely confused about all instances where the a character is used. someone please explain. i'm also confused about the declaration of the int i variable in the for loop and the usage of before the conversion method. how exactly does this variable translate into the elements of the array that i would use the method to declare?

Let's just break the code down.

Spoiler

// Function, which will return an int array to whoever called it.
// You can see it returns it, by seeing the 'int[]' at the start. 'ReturnUserInput' is the name of function.
int[] ReturnUserInput()
{
	// Making an int array, containing up to 3 values (at index 0, 1 and 2).
	int[] a = new int[3];
	// A for loop, loops through all the values of array 'a'.
	//You can translate this to:
	// i++ just adds 1 to the contents of i, i is declared at the start of the line as zero. 
	//If i is smaller than the length of 'a' (the array with length 3, declared above), do the code in the for loop. 
	for (int i = 0; i < a.Length; i++)
	{
		Console.Write("Enter an integer: ");
		// array 'a', at index i (which will be 0, the first time this code is ran, 1 the second time, 2 the third and last time)
		// Store the user data there.
		a[i] = Convert.ToInt32(Console.ReadLine());
		// Write a line (\n means next line, so 'enter' on your keyboard basically).
		Console.WriteLine("Integer added to array.\n");
	}
	// This loop above is ran 3 times, because that is the length of array 'a', 
	// it requests a user input these three times and whatever the userinput is, it fills it in the array.
	// The line below returns this array.
	return a;
}

// Call the function listed above, make it return whatever it returns into "myArray2".
int[] myArray2 = ReturnUserInput();

// this line below does nothing, it waits for user input, so your program doesn't just stop after doing all above.
Console.ReadLine();

 

Kind of putting it most simply:

Spoiler

 


Call Function "Make array" and place it in "myArray" (which is of type int):

Make Array Function:
{
	create array "userInputArray", which will house up to 3 integer values.
    
    counter is declared at value 0
    counter goes up once every time this code is run (counter++), 
    it runs it as many times as myFunctionArray is large (counter < userInputArray.Length/ < = smaller than)
    {
    	Write "please fill in a number"
    	So which every entry of the array I am at, insert the user's input.
    	userInputArray[counter] = userinput
        write "number has been added"
    }
    This code is done three times, at index 0, 1 and 2.
    Afterwards 'userInputArray' is returned to where I called it.
}    

With this type of, as a beginner I personally always went through it step by step, kind of translating what was going on.

Writing it down might help too.

 

 

 

Quote

i'm also confused about the declaration of the int i variable in the for loop and the usage of before the conversion method. how exactly does this variable translate into the elements of the array that i would use the method to declare?

i in kind of the default variable name used in for loops, because a longer name is often not necessary (a for loop does a simple defined thing, so it's typically clear what 'i' means in the context of such a loop).

I am not sure what you are asking with this question further, so if I didn't make it clear what 'i' (or counter in my 'simple language' code conversion), could you ask the question again in a different way?

 

If you have any other questions, or if I didn't explain anything clear enough, please do tell me! I can only learn from it :P 

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to comment
Share on other sites

Link to post
Share on other sites

 void PrintFirstElement(int[] a)
            {
                Console.WriteLine("The first element is {0}.", a[0]);
            }
            int[] myArray = { 1, 2, 3, 4 };
            PrintFirstElement(myArray);
            Console.ReadLine();

the "a" int "int[] a" is the name of the parameter of this function. You could change it to basically anything you want. The reason you need a name for it is so that you can actually work with it as seen in the WriteLine() function. The "{0}" in the text is just telling the function that it should take the second parameter (in this case the a[0] which indicates the first element in the Array, in this case the 1. ) and put its value into the text. Btw you should be able to do something like this:

Console.WriteLine("{0} {1} {2} {3}", "This", "is", "a", "text.");

And it should write to the console: "This is a text." .

 

With the second function, let's go through the code line by line:

int[] ReturnUserInput()

This is the head of the function. Instead of "void" it has int[] defined as the return type. That means once this function is done running it will return an int[] object.

Note that the return type does not have a name like the parameter in the function before. This is because we are only able to return one object like this.

int[] a = new int[3];

Here we create a new object of type int[], which is an array of integer numbers, with a length of 3 elements. No elements are defined yet though. So I think the array would be filled with 0's at this point in time. You need to do this so you have an array to work on.

for (int i = 0; i < a.Length; i++)

This is the head of the for-loop which starts here. In case you  haven't learned what a for loop is yet:

A for-loop consists of 3 parts:

for(this is done before the loop starts its first run; some kind of condition ; this is done after each run through the loop)

//Most of the time it looks like this:

for(int i = 0; i < something; i++)

As the name states a for-loop repeats lines of code over and over again. But before it starts it first defines a variable, in this case i, and gives it a starting value. Now as long as the condition, in this case i < something, is true it will run the code in the body of the for loop. After it has run the code in the loop it then executes the line written at the end of the for-loop head, in this case i++ (i++ is a shorter version of i = i + 1,  so i will get 1 added to it) . All of this means that the loop will be executed a fixed amount of times. And you have a variable, in this case i, to check how often the loop has already been run through.

Console.Write("Enter an integer: ");
a[i] = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Integer added to array.\n");

This is the key part of this function. What effectively happens here is the following: The console asks the user to write a number which the programm then stores in the array, which is named "a" (again, you could name the array anyway you want). a just means the array at position i. And because our for-loop has defined that i will start from 0 and will go as long as i is smaller then the length of a (in this case 3, so the loop would stop once i becomes 3 because 3 < 3 is false. ). And each time it will ask the user to write a number. But Console.ReadLine() returns a String, not an int object. Therefore you have to change it to an int object. That's why there is "Convert.ToInt32()" . This function changes the string to an int, if it can (if the string is a number it can, else it would probably throw an error or something). This entire process is repeated a.length times.

Then it finally returns the array by doing this:

return a;

What this does is tell the function to take the array "a" and return it, this is necessary because else the function would not know which array to return (if you had used more than one array). So if you would do something like this:

int[] myArray2 = ReturnUserInput();

"a" would effectively end up in "myArray2".

 

If you need help understanding the for loop better try changing it to this:

for (int i = 0; i < a.Length; i++)
{
	Console.WriteLine("i is {0} \n",i);
	Console.Write("Enter an integer: ");
	a[i] = Convert.ToInt32(Console.ReadLine());
	Console.WriteLine("Integer added to array.\n");
}

Now the code will write the value of i to the console and you can keep track of it.

Link to comment
Share on other sites

Link to post
Share on other sites

thanks everyone for the help. i pretty much understand both methods enough to work with the code properly now.

 

there is one concept about the second method that still confuses me. it's not a problem with understanding how the code works, it's more about understanding why the code works the way that it does. i'll post the method below and explain as best i can. i'm still new to programming lingo so i might not be able to work this clearly or properly.

 

            int[] ReturnUserInput()
            {
                int[] a = new int[3];
                for (int i = 0; i < a.Length; i++)
                {
                    Console.Write("Enter an integer: ");
                    a[i] = Convert.ToInt32(Console.ReadLine());
                    Console.WriteLine("Integer added to array.\n");
                }
                return a;
            }
            int[] myArray2 = ReturnUserInput();
            Console.ReadLine();

so as i said before. thanks to you guys i understand the way that this method works and how to manipulate the code here. my confusion is about the concept of why the int i variable in the for loop works the way that it does.

 

how exactly does c# know that the for loop is accessing the positions of the elements in the array 'a' by using the variable int i to represent the element position in the array?

 

to put it differently, how does c# know that the value of int i is representative of the corresponding element positions in the array 'a'?

Link to comment
Share on other sites

Link to post
Share on other sites

If you look closely at the following line:

a[i] = Convert.ToInt32(Console.ReadLine());

Here the programmer specifies that the input should be stored in position i of the array a.

And again, you do not have to use "i" for this, you could do something like this if it helps you understand the code better:

int[] ReturnUserInput()
            {
                int[] a = new int[3];
                for (int positionInArray = 0; positionInArray < a.Length; positionInArray++)
                {
                    Console.Write("Enter an integer: ");
                    a[positionInArray] = Convert.ToInt32(Console.ReadLine());
                    Console.WriteLine("Integer added to array.\n");
                }
                return a;
            }

This would work exactly like the code in the book. "i" is just another variable like any other variable in your code.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×