jmooremcc

C Number Frequency Exercise

Sep 29th, 2019
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.05 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3.  
  4. typedef struct _counter {
  5.     int number;
  6.     int count;
  7. } CountRecord;
  8.  
  9. #define MAXNUMBERS  5
  10.  
  11. int main()
  12. {
  13.     int i, j, number;
  14.     // declare and init data array
  15.     CountRecord data[MAXNUMBERS];
  16.  
  17.     // Fields in the structure are initilized to zero (0)
  18.     for (i = 0; i < MAXNUMBERS; i++)
  19.         data[i].number = data[i].count = 0;
  20.  
  21.     // Get each number and process it
  22.     for (i = 0; i < MAXNUMBERS; i++) {
  23.         scanf_s("%d", &number); // Get a number
  24.  
  25.         //If the number is not already in the data array, then add it along with incrementing the count
  26.         for (j = 0; j < MAXNUMBERS; j++) {
  27.             if (data[j].number == 0) {
  28.                 data[j].number = number;
  29.                 data[j].count++;
  30.                 break;
  31.             }
  32.             else if (data[j].number == number) { // The number exists in the data array, increment the count
  33.                 data[j].count++;
  34.                 break;
  35.             }
  36.         }
  37.     }
  38.  
  39.     // Print the data array to the console
  40.     for (i = 0;i < MAXNUMBERS;i++) {
  41.         if (data[i].number != 0)
  42.             printf("%d:%d\n", data[i].number, data[i].count);
  43.         else
  44.             break;
  45.     }
  46.    
  47.     return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment