Write a program that returns the sum of positive elements of
Write a program that returns the sum of positive elements of an array of integers. Rewrite this with a function called sum that takes an array and returns the sum.
Write a program that returns the sum of positive elements of an array of integers. Rewrite this with a function called sum that takes an array and returns the sum.
Solution
//This is first method, without using functions.
int main()
{
int array[] = {1, 2, 3, 4, 5};
int sum = 0;
for(int i = 0; i < 5; i++)
sum += array[i];
printf(\"The sum of elements in the array is: %i\ \", sum);
}
//This is second method, using functions.
int sum(int array[], int count)
{
int s = 0;
for(int i = 0; i < count; i++)
s += array[i];
return s;
}
int main()
{
int array[] = {1, 2, 3, 4, 5};
printf(\"The sum of elements in the array is: %i\ \", sum(array, 5));
}
