Home > Software design >  C program histogram print results only once
C program histogram print results only once

Time:12-08

If I inter array for example [1,1,1,2] program would print:

Number 1 appears 3 times.

Number 1 appears 3 times.

Number 1 appears 3 times.

Number 2 appears 1 times.

And it should print:

Number 1 appears 3 times.

Number 2 appears 1 times.

How to fix this?

#include <stdio.h>

int main() {
    int i,arr[1000],counters[1001]={0},n;
    printf("Enter numbers: \n");
    for(i=0;i<100;i  ){
        scanf("%d", &arr[i]);
        if(arr[i]==-1) break;
        if(arr[i]<0||arr[i]>100){
            printf("Numbers must be between 0 and 100\n");
            i--;
        }
    }
    n=i;

    for(i=0;i<n;i  ){
        counters[arr[i]]  ;
    }

    for(i=0;i<n;i  ){
        printf("Number %d appears: %d times\n", arr[i], counters[arr[i]]);
    }
    

    return 0;
}

CodePudding user response:

You're looping over the total number of inputs, so you get 4 lines of output in this particular case. However, since you're working with a relatively small number of non-negative integers, you can simplify your program quite a bit by making the indices represent the inputs, like so:

#include <stdio.h>


int main() {
  int arr[101]={0}, n;
  printf("Enter numbers (end with -1): \n");
  while (1) {
    scanf("%d", &n);
    if(n==-1) break;
    if(n<0 || n>100) {
      printf("Numbers must be between 0 and 100\n");
      continue; 
    }
    arr[n]  ; 
  }
  
  for(n=0;n<=100;n  ){
    if (arr[n]) printf("Number %d appears: %d times\n", n, arr[n]);
  }

  return 0;
}

CodePudding user response:

Instead of traversing the array having multiple occurrences of the same number, increment the iterator by the number of occurrences to jump to the next number immediately:

for(i=0;i<n;i = counters[arr[i]]){
    printf("Number %d appears: %d times\n", arr[i], counters[arr[i]]);
}

CodePudding user response:

Iterate trough the counter array and print the counters > 0

for (i = 0; i < 100; i  ) 
{
    if (counters[i])
    {
        printf("Number %d appears: %d times\n", i, counters[i]);
    }
}
  • Related