Public feed
#599116
//Note: this provides a nice way to loop through arrays! Observe this function below.
sum_of_array(myArray[], size)
{
//Note: Make sure the user passes the size of the array, so we don't overflow it.
new i, sum
//This loop will start at 0 and stop right before size is reached.
//If the user passes the correct size of the array,
// the loop will be going from 0 to size-1
// This correctly matches the numbers of slots in the array.
for (i=0; i<size; i++)
{
//For every time this loop executes,
// i will be a number from 0 to size-1
//Add the value of the slot (i) in the array to sum.
//Once this is finished, sum will contain
// the sum of all slots in the array.
sum += myArray[i]
}
return sum
}
new NumberArray[4]
NumberArray[0] = 3
NumberArray[1] = 1
NumberArray[2] = 4
NumberArray[3] = 1
new answer = sum_of_array(NumberArray, 4)
//answer will be 3+1+4+1, or 9