We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I am trying to make a program that sums the individual elements of an array of 10 numbers. In order to calculate the sum I must create a function "Sum function" that returns the value corresponding to the sum of the elements of an array.Then print the entire array on the screen, and the sum. But I don't understand how to use the return function in this specific exercise. Can someone help me to understand and create the function sum? Thank you a lot.
void setup()
{
size(400, 400);
background(#0047b3);
noLoop();
}
void draw()
{
int[] numbers={14, 7, 90, 5, 8, 42, 128, 64, 12, 3};
for (int i=0; i<numebers.length; i++)
{
print(numeri[i]+", ");
}
println();
println("Sum = "+sum(numbers));
}
Answers
int sum( int... arr1) {
for.....
iirc
then create a function. currently everything is within draw() which isn't what you want.
move the calculation to another method. see reference for
return
for an example.https://processing.org/reference/return.html
(in fact, look at the second example there, it's passing in an array)
Hi Chris, thank you for your help but I am sorry I don't understand. Do you mean something like
int sum(int...arr1) { for (int i =0; i<f.length; i++ ) { ? }
and then?
ps. Thank you Koogs, I read the reference but it didn't help me. Maybe I am confused.
Do you know what a function is?
setup and draw are functions.
Like a function in math.
The receive some value and return a value.
In your case array goes in and int comes out.
Anyway.
int sum above is the name of the function sum and what it returns
int sum (int[] array1) {
int returnValue;
for loop like yours above but with array1.length ) {
returnValue=......
}
} // function
Thank you a lot. I finished my exercise:
well done, MirielLind
;-)
Thank you a lot Chris. Thanks a lot for all the help from the forum. ;)