C programming: do not need entire program just the user-defined function Write a
ID: 3828738 • Letter: C
Question
C programming: do not need entire program just the user-defined function
Write a user-defined function called AddPositive that receives two parameters: an array of integers, and an integer that contains the number of elements in the array. The function adds only the positive values that appear in the array and returns the total. Example: if array contains 2,-1,-4, 66,71, -10 the function would return the number 139 since the sum of the positive numbers, 2,66, and 71 is 139. (Hint: a conditional statement in your loop)
Explanation / Answer
int AddPositive(int arr[], int size)
{
int sum = 0; //initialize sum as 0.
int i;
for(i=0;i<size;i++) //start for loop to loop through the array till its size
{
if(arr[i] > 0) // check if the particular element in array is +ve or not
{
sum = sum + arr[i]; //add +ve elements of array to the sum value
}
else {
sum = sum + 0; //this else part is not essential but better to provide one and have a habit of writing them. //if -ve elements are there, we shall add 0 to the current sum value.
}
}
return sum;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.