Write a function that prints all the values that occur in an array and the numbe
ID: 3858839 • Letter: W
Question
Write a function that prints all the values that occur in an array and the number of times each value occurs. Below is an output sample. The function takes as parameters the array and its size. The 'main' function should declare the array and fills it with random numbers that are between 0 and 10, inclusive. Write your program using a symbolic constant 'SIZE' so that your code can be modified to any size array simply by changing 'SIZE' on top of the code. Array: 10 4 7 4 2 7 10 4 4 0 4 Value 10: 2 times Value 4: 5 times Value 7: 2 times Value 2: 1 times Value 0: 1 timesExplanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 10
void printArrayElementsCount(int a[], int n) {
int i,j,k;
int count = 0;
int isDisplayed = 0;
for(i=0;i<n;i++) {
count = 0;
isDisplayed = 0;
for(k=0;k<i;k++) {
if(a[i]==a[k]) {
isDisplayed = 1;
break;
}
}
for(j=0;j<n && isDisplayed == 0; j++) {
if(a[i]==a[j]) {
count++;
}
}
if(isDisplayed==0) {
printf("Value %d: %d ",a[i],count);
}
}
}
int main()
{
int array[SIZE];
int i;
srand (time(NULL));
for(i=0;i<SIZE;i++) {
array[i] = rand() % 10 + 1;
}
printf("Original data ----------------- ");
printf("Array: ");
for(i=0;i<SIZE;i++) {
printf("%d ", array[i]);
}
printf(" ");
printArrayElementsCount(array, SIZE);
return 0;
}
Output:
sh-4.2$ gcc -o main *.c
sh-4.2$ main
Original data
-----------------
Array: 1 9 2 7 6 4 1 8 7 5
Value 1: 2
Value 9: 1
Value 2: 1
Value 7: 2
Value 6: 1
Value 4: 1
Value 8: 1
Value 5: 1
sh-4.2$ main
Original data
-----------------
Array: 8 8 1 1 3 3 4 8 2 10
Value 8: 3
Value 1: 2
Value 3: 2
Value 4: 1
Value 2: 1
Value 10: 1
sh-4.2$ main
Original data
-----------------
Array: 9 7 10 4 1 1 10 8 10 4
Value 9: 1
Value 7: 1
Value 10: 3
Value 4: 2
Value 1: 2
Value 8: 1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.