Greetings, everyone i have trouble with this exercise in programming C. Write a
ID: 3838792 • Letter: G
Question
Greetings, everyone i have trouble with this exercise in programming C. Write a user-defined function called CountPositive that receives two parameters: an array of integers, and an integer that contains the number of elements in the array. The function counts the number of positive values that appear in the array and returns it. 0 is a positive number Example: if array contains 2,-1,-4, 66,71,0 the function would return the number 4 since there are 4 positive numbers in the array. (Hint: a conditional statement in your loop)
my ans was (it was wrong):(Response Feedback:
perhaps you should read the question before)
Int main()
{
int array[] = {1, 2, 3, 4, 5, -4, -6, -8, 0};
int pos, neg;
CountPositive(9, array, &pos, &neg);
return 0;
}
void CountPositive(int num, int * arr, int *pos,int *neg)
{
int i = 0;
*pos = 0;
*neg = 0;
for(i = 0; i < num; i++)
{
if(*(arr + i) >= 0)
(*pos)++;
else
(*neg)++;
}
return;
}
Explanation / Answer
#include<stdio.h>
#include<string.h>
int CountPositive(int num, int arr[]);
int main()
{
int array[] = {2,-1,-4, 66,71,0};
int posCount;
posCount = CountPositive(6, array);
printf("Number of positive numbers: %d ", posCount);
return 0;
}
int CountPositive(int num, int arr[])
{
int i = 0;
int count = 0;
for(i = 0; i < num; i++)
{
if(arr[i] >= 0)
count++;
}
return count;
}
Output:
sh-4.2$ gcc -o main *.c
sh-4.2$ main
Number of positive numbers: 4
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.