Question

Why does the following code give me 25 instead of 10 when placing count++ after each case statement? Also, is there a built in function in C to determine the length of an array like in Python?

#include <stdio.h>
#include <stdlib.h>

int count_prime(int X[], int size);

int main() {
    int X[] = {4,5,3,7,9,65,17,8,7,4,2,5,6,8,5,3,3,245,10,9,4,2,9};
    int size = 23;
    count_prime(X,size);
    return 0;
}

int count_prime(int X[], int size) {
    int i;
    int count=0;
    for (i = 0; i < size; i++) {
        switch(X[i]) {
            case 2:count++;
            case 3:count++;
            case 5:count++;
            case 7:count++;
        }
     }
     printf("%d",count);
     return count;
}
Was it helpful?

Solution

You are missing break statements, so you code falls-through (ie: cascades) for each statement. Also, you are missing a default case, which is poor form, and should be corrected. Make the switch this:

    switch(X[i]) {
        case 2:count++;
               break;
        case 3:count++;
               break;
        case 5:count++;
               break;
        case 7:count++;
               break;
        default:
               break;
    }

Finally, you can make your code a bit safer by replacing:

int size = 23;

With:

int size = sizeof(X) / sizeof(int);

A word of caution when using the sizeof function: if you are using it on a function parameter, it will fail due to "pointer decay", a topic worth reading up on.

OTHER TIPS

You're missing break statements, so it's falling through all the following cases whenever it matches one of the cases.

    switch(X[i]) {
        case 2:count++;break;
        case 3:count++;break;
        case 5:count++;break;
        case 7:count++;break;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top