Write a program that reads N integers into an array. Then prints on a separate l
ID: 3534609 • Letter: W
Question
Write a program that reads N integers into an array. Then prints on a separate line the value of each distinct element along with the number of times it occurs. The values should be printed in descending order. One solution to this problem is to get input numbers and store them in array A. Then traverse this array A to find distinct number and the times they occur. Finally, sort all distinct numbers (with the times they occur).
Requirement:
 Your program shall be able to process at least 20 integers as input;
 You don’t have to investigate the output of rand(); Hint:
 You can declare an array of size larger or equal to 20 to store input ints;
 You can either ask ahead for the number of ints user is going to input, like following:
 To store distinct ints and the times they occur, you can use two more arrays. For example, distinctArray[0] stores -7, and timesOccur[0] stores 2 for the previous input. You can also store one distinct int and the time it occurs with one structure variable and declare a structure array, but this is not requirement.
 To sort distinct ints, you can use bubble sort. Please refer to section 9.6 on page 313 of your textbook for more detail.
Example:
This program counts the number of times distinct input number occurs. How many input numbers are there?
Please input 10 numbers
5 occurs 2 times
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[20];
int no_of_int,i,temp,j;
int count[20];
printf(" This program counts the number of times distinct input number occurs. How many input numbers are there? ");
scanf("%d", &no_of_int);
printf(" please input %d numbers " , no_of_int);
for(i=0; i<no_of_int; i++)
{
scanf("%d",&a[i]);
count[i] = 1; // intalize count to 1.
}
// now sort data using buble sort. :(
for (i = 0; i < no_of_int; i++) {
for (j = i+1; j < no_of_int; j++) {
if (a[j] > a[i]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
// now count repeated elements.
for (i = 0; i < no_of_int; i++)
{
if (count[i] == 0)
{
continue;
}
for (j = i+1; j < no_of_int; j++)
{
if (a[j] == a[i])
{
count[i] += 1;
count[j] = 0;
}
}
}
//now print values
for (i = 0; i < no_of_int; i++)
{
if(count[i]>0)
printf("%d Occur %d times ", a[i], count[i]);
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.