umbraatrox
umbraatrox

Reputation: 3

Comparing arrays in a function

My function countCopies doesn't work even though it gets the right inputs. All it should do is taking an array of integers as an input and then searching through this array for duplicates of the second input x.

int main() {
    char intArray[100]; //The integer array can only hold 100 integers
    int i, x, j;
    printf("Please enter a couple of integers and when you're done enter end. ");

    i = 0;
    while (scanf("%d", &intArray[i++]) == 1)
        /*empty loop*/;

    scanf("%*s");

    printf("Enter x:");
    scanf("%d", &x);

    printf("Copies = %d\n", countCopies(intArray, i, x));
}

int countCopies(int a[], int n, int x) {
    int count = 0;
    int j = 0;
    for (j = 0; j < n - 1; j++) {
        if (a[j] == x) {
            count++;
        }
    }
    return count;
}

Upvotes: 0

Views: 67

Answers (2)

chqrlie
chqrlie

Reputation: 144550

The for loop is incorrect: you should change the test to j < n. The idiomatic for loop in C: for (j = 0; j < n; j++) ... iterates exactly n times, j taking values 0 to n-1 inclusively, which are correspond to exactly all valid positions in an array of n elements.

Note that the array has the wrong element type: it should be int, not char. You should also check for array bounds in the first loop and for conversion success of the last scanf.

Here is a corrected version:

#include <stdio.h>

int countCopies(int a[], int n, int x);

int main(void) {
    int intArray[100]; //The integer array can only hold 100 integers
    int i, x;

    printf("Please enter a series of integers, end the list with the word end.\n");

    for (i = 0; i < sizeof(intArray) / sizeof(*intArray); i++) {
        if (scanf("%d", &intArray[i]) != 1)
            break;
    }
    if (scanf("%d", &x) == 1) {
        printf("too many numbers\n");
        return 1;
    }
    scanf("%*s");  /* skip the end word.  Note that any word is OK */

    printf("Enter x:");
    if (scanf("%d", &x) == 1) {
        printf("Copies = %d\n", countCopies(intArray, i, x));
    }
    return 0;
}

int countCopies(int a[], int n, int x) {
    int j, count = 0;

    for (j = 0; j < n; j++) {
        if (a[j] == x) {
            count++;
        }
    }
    return count;
}

Upvotes: 2

catalogue_number
catalogue_number

Reputation: 335

To expand on chqrlie's answer,

The code for (i = 0; i < n; i++) {/* do stuff */} executes in the following order:

  1. The variable i is set to zero.
  2. The conditional i < n is tested. If true, the code in /* do stuff */ is executed, otherwise, the loop is exited.
  3. The increment i++ is applied.
  4. Go back to 2.

That means that on the loop iteration when i gets incremented to n, the for loop breaks before the code inside the loop gets executed, so if you're accessing an array with n elements, the last element that gets accessed has the index n - 1. Hence the C loop paradigm that chqrlie mentioned.

Upvotes: 1

Related Questions