Given an integer array that uses a sentinel value to indicate the end of values,
ID: 3830911 • Letter: G
Question
Given an integer array that uses a sentinel value to indicate the end of values, and can contain anywhere from 10 to 10,000,000 values, such as
short quartile[ ] = { 1, 3, 2, 4, 1, 3, 1, 4, 1, 4, 4, 1, 1, 1, 4, 2, 4, 1, 1, 4, 1, 3, 1, 1, 1, 4, 1, 1, 4, 1, 1, 1, 1, 4, 1, 1, 4, 1, 2, 5, 1, 1, 0 };
2. Write a complete function to count how frequently a given value appears in an array and returns that count such that the following C code would work:
int findvalue = 2;
printf( "The value %d occurs %d times. ", findvalue, countOccurances( quartile, findvalue ) );
If the value to find doesn't appear in the array, return zero.
Explanation / Answer
#include <stdio.h>
int countOccurances(int a[], int findvalue) {
int i, count = 0;
for(i=0; a[i]!=0;i++){
if(a[i] == findvalue){
count++;
}
}
return count;
}
int main()
{
int quartile[ ] = { 1, 3, 2, 4, 1, 3, 1, 4, 1, 4, 4, 1, 1, 1, 4, 2, 4, 1, 1, 4, 1, 3, 1, 1, 1, 4, 1, 1, 4, 1, 1, 1, 1, 4, 1, 1, 4, 1, 2, 5, 1, 1, 0 };
int findvalue = 2;
printf( "The value %d occurs %d times. ", findvalue, countOccurances( quartile, findvalue ) );
return 0;
}
Output:
sh-4.2$ gcc -o main *.c
sh-4.2$ main
The value 2 occurs 3 times.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.