Complementary task for topic: 3

M Nemeth · 2023-08-29 15:21:04.616219'

Arrays: Number Occurrences Table

Arrays: Number Occurrences Table

Write a C program that reads numbers from the standard input as long as they are valid (fall between 1 and 10). The program should count the occurrences of each number and print the result to the standard output in a tabular format.

Hint: Like in practice, the array can contain the occurrences, while the input is valid.

Solution
#include 

#define SIZE 10

int main() {
    int numbers[SIZE] = {0};  // Initialize the array to store occurrences of numbers
    int input;
    
    printf("Enter numbers between 1 and 10 (0 to stop):\n");
    
    while (1) {
        scanf("%d", &input);
        
        if (input == 0) {
            break;  // Exit the loop if 0 is entered
        }
        
        if (input >= 1 && input <= 10) {
            numbers[input - 1]++;  // Increment the count for the entered number
        } else {
            printf("Invalid input. Please enter a number between 1 and 10.\n");
        }
    }
    
    printf("\nNumber\tOccurrences\n");
    printf("------------------\n");
    
    for (int i = 0; i < SIZE; i++) {
        if (numbers[i] > 0) {
            printf("%d\t%d\n", i + 1, numbers[i]);  // Print the number and its occurrences
        }
    }
    
    return 0;
}



Explanation
In this example, the program uses an integer array numbers of size SIZE to store the occurrences of numbers from 1 to 10. The array is initialized to all zeros.

The program continuously reads numbers from the standard input using a while loop until the user enters 0. Inside the loop, the entered number is checked for validity (between 1 and 10). If it is valid, the corresponding count in the numbers array is incremented. If it is not valid, an error message is displayed.
< < previous    next > >