I’m a bit in a problem. I’m supposed to get this function to work for the followings array, but I only get it to work it one. Perhaps I’m not thinking right, or it’s easier than I’m trying to it to be. Anyone that has any idea, would really be appreciated…
Please, use the little </> icon above the text box to format the code into actual code, so that it would look better in the comments, i.e. like this.
Anyways, the problem in your function is that it only does it for numbers 0, 1, 2 and 3 - and not any more. Shouldn’t it also read number 4, 5, 6, however many of them are there?
The solution is the for loop, which can iterate over all numbers of an array no matter how long or short it is. The syntax for for loop is simple: for(counter variable declaration; condition to stop the loop; increment of the variable){...
For example:
for(int i=0; i < 5; i++){
println( i );
}
This will go through all numbers up until 5, and will print 0 1 2 3 4. You can change that 5 to any number, or even a variable that is a number, and have it do its thing as much as you need.
So, in your function, I suggest doing just float sum = 0;, and then using a for loop to add all of numbers from the array to the sum variable.
I understand that I should use a for loop, but don’t understand how I will the two arrays, to preform the same meanvalue function and get two return types. I’ve tried many types but never got the hang of it…
I’m sorry that I that I don’t completely understand this, but it is what is is
I don’t think I understand your question completely, but I will try saying random things that could help.
A way to use the for loop for this function is like this:
float meanvalue(float[] a){
float sum = 0;
for(int i=0; i<a.length; i++){
sum = sum + a[i];
}
sum = sum / a.length;
return sum;
}
This way, every single value inside of any array you give to it gets added, and a mean value is returned. The name for the input array in the function definition does not matter completely, as long as you don’t confuse it with values that are outside of the function.
So, now you can do println(meanvalue(number1)); and println(meanvalue(number2));, and both will work with this function.
Hello again, if anyone has time or a tip to what I’m doing wrong here again. So this code is a follow up to the one above, but in this case the user will decide how many values the array can have and what these values are. However, I only get it to write them out once and the function doesn’t work with with then. (It probably has something to do with the first for loop, but I don’t know how exactly