Complementary task for topic: 3

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

Arrays: Element Count

Arrays: Element Count

Write a C program that prompts the user to enter an integer array of size 10 and a target number. The program then counts and displays the number of occurrences of the target number in the array.

Hint: Watch out for the indices! In the second loop you can use one index to traverse (and back traverse), but as in the example, you can use two in one loop!

Solution
#include 

#define SIZE 10

int main() {
    int numbers[SIZE];
    int target;
    int count = 0;
    
    printf("Enter %d integers for the array:\n", SIZE);
    
    for (int i = 0; i < SIZE; i++) {
        scanf("%d", &numbers[i]);
    }
    
    printf("Enter the target number to count: ");
    scanf("%d", &target);
    
    for (int i = 0; i < SIZE; i++) {
        if (numbers[i] == target) {
            count++;
        }
    }
    
    printf("Number of occurrences of %d in the array: %d\n", target, count);
    
    return 0;
}



Explanation
In this example, the program declares an integer array numbers of size SIZE, which is set to 10 using the #define directive.

The program prompts the user to enter SIZE number of integers for the array using scanf() within a for loop. Each input is stored in the corresponding index of the numbers array.

Next, the program prompts the user to enter the target number to count the occurrences of using another scanf().

A for loop is then used to iterate over the array and count the number of occurrences of the target number. The count variable is used to store the count.
< < previous    next > >