Write a program that reads in an array of type int. You may assume that there ar
ID: 3555705 • Letter: W
Question
Write a program that reads in an array of type int. You may assume that there are fewer
than 50 entries in the array. Your program determines how many entries are used. The
output is to be a two-column list. The first column is a list of the distinct array elements;
the second column is the count of the number of occurrences of each element. The list
should be sorted on entries in the first column, largest to smallest.
For the array values:
-12 3 -12 4 1 1 -12 1 -1 1 2 3 4 2 3 -12
the output should be
N Count
4 2
3 3
2 2
1 4
-1 1
-12 4
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#define SIZE 50
/* this comp function is used in qsort ,you have to modify it
here if returning value is less than zero than a comes first in comaprison and vice versa*/
int comp (const void * a, const void * b)//argument takes a void * pointer and then convets them to an integer pointer
{
return ( *(int*)b - *(int*)a );
}
int main ()
{
int vett1[SIZE], vett2[SIZE];// two arrays one for storing numbers and another for storing count
int n, i, j;
int flag;
printf ("Imput n: ");
scanf ("%d", &n);//asking for total numbers of input
printf ("Imput numbers ");
for (i=0; i<n; i++)
{
scanf ("%d", &vett1[i]);//storing values in array vett1
}
qsort(vett1,n,sizeof(int),comp) ;/* qsort is built in function used to sort an array it takes an array
,number of elements in array,size of members of arrray, and a comparison function to compare two numbers
here the function comp we defined above when used it sorts array in decresing order because suppose in comp function a=2,b=5
then b-a will be positive so a will go after b*/
for (i=0; i<n; i++)
{
flag=0;
for (j=0; j<n; j++)
{
if (vett1[j] == vett1[i])
{
flag++;
}
}
vett2[i] = flag;//vett2 contains count of each number in repetedlyeg if araay vett1is [1,1,1,2] then vett2 is [3,3,3,1]
//that is count of every number
}
printf (" ");
printf (" Count N ");
printf (" %d %d ", vett1[0], vett2[0]);//we are printing count of first element
for (i=1; i<n; i++)
{
if(vett1[i]!=vett1[i-1])
printf (" %d %d ", vett1[i], vett2[i]);
//we are checking if previous number is not same as cureent number then printing the count
}
system("pause");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.