Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that reads the integers between 1 and 100 and counts the occurre

ID: 3631866 • Letter: W

Question

Write a program that reads the integers between 1 and 100 and counts the occurrences of each. Assume the input ends with 0. Here is a sample run of the program:

Enter the integers between 1 and 100: 2 5 6 5 4 3 23 43 2 0
2 occurs 2 times
3 occurs 1 time
4 occurs 1 time
5 occurs 2 times
6 occurs 1 time
23 occurs 1 time
43 occurs 1 time

Note that if a number occurs more than one time, the plural word "times" is used in the output.

You must get (and verify) user input in its own method.
You must print the program output in its own method.
Other methods (including main!) may need to be created.

Explanation / Answer

JAVA

import java.util.Scanner;
public class OccurrenceOfNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] count = new int[100];
int j = 0;
for (j=0; j<100; j++)
     count[j] = 0;
System.out.print("Enter the integers between 1 and 100:(0 to exit) ");
j = input.nextInt();
while(j!=0)
{count[j]++;
j = input.nextInt();
}
for (j=0; j<100; j++)
         if (count[j] != 0)
             {System.out.print(j+" occurs "+count[j]+" time");
            if(count[j]>1)
              System.out.println("s");
             else
              System.out.println("");
      }
}
}

C Program

int array[100];
initialize the whole array with 0 using a loop;

int i = 0;

for( ; i <= 100; i++)
array[i] = 0;

Now just have a loop for users to enter values and then go to that value's spot in the array and increment it to count. Have them enter 0 when done.

printf("Enter integers between 1 and 100. Enter 0 when done ");
while(i != 0)
{
scanf("%d", &i);
if(i > 0)
array[i-1]++; //note since array count starting with 0 you array[5] would be for 6 for example.
}

Then simply loop through the array when printing how many times it occurs and use an if to print times instead of time for values greater than 1;

for(i = 0; i < 100; i++)
{
if(array[i] > 0)
{
if(array[i] > 1)
printf("%d occurs %d times ", i+1, array[i]);
else
printf(%d occurs 1 time ", i+1);
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote