Home > front end >  counting the number of 7s in the array
counting the number of 7s in the array

Time:01-31

I'm really close to figuring out a problem given to me in a c course and am having trouble trying to count the number of 7's in the output array. The count isn't updating in my output.

This is the code:

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

#define  ARRAY_SIZE 25
#define  ENTRY_SIZE 10
#define  QUIT_ENTRY  -9999

int main( int argc, char * argv[] ) {
    char input[ENTRY_SIZE];
    char array[ARRAY_SIZE];
    char output[ENTRY_SIZE * ARRAY_SIZE] = "";
    double average = 0.0;
    int sum = 0;
    int j; //size of the full array
    int count =0;
    int changeInput;
    int i; //the count for the input array

    printf("Enter a number 1 at a time or enter -9999 to finish entering numbers. \nEnter a total of 25 numbers. \n");
    fflush( stdout );
    for (i = 0; i < ARRAY_SIZE; i  )
    {
        printf("Enter: ");
        fflush( stdout );
        changeInput = atoi( gets( input ) );
        if(changeInput == QUIT_ENTRY)
        {
            break;
        }
        array[i]=changeInput;
    }
    for (j = 0; j < i; j  )
    {
        sum = sum   array[j];
    }
    average = (double)sum/i;

    memcpy(output, array, strlen(array));

    for (i = 0; i < j; i  )
    {
        if (array[i] == '7')
            count  ;
    }

    printf("\nThe sum of numbers is: %d", sum);
    fflush( stdout );
    printf("\nThe average of the numbers is: %f", average);
    fflush( stdout );
    printf("\nThe long string of values is: ");
    fflush( stdout );

    for (int z = 0; z < j; z  ) {
        printf("%d",output[z]);
    };
    printf("\nThere are %d 7's.", count);
    fflush( stdout );

return 0;
}

And here's the output:

Enter a number 1 at a time or enter -9999 to finish entering numbers.
Enter a total of 25 numbers.
Enter: 1
Enter: 2
Enter: 3
Enter: 4
Enter: 5
Enter: 6
Enter: 7
Enter: 8
Enter: 9
Enter: -9999

The sum of numbers is: 45
The average of the numbers is: 5.000000
The long string of values is: 123456789
There are 0 7's.

There should be 1 7 in the result at the bottom but it returns 0 to me. Any help is appreciated.

I'm not sure how else to do the codeblock here:

    for (i = 0; i < j; i  )
    {
        if (array[i] == '7')
            count  ;
    }

If I were to guess my problem lies somewhere else, but I'm new to c and am not sure.

EDIT 1: I did as suggested in the answer below and realized that the count is only counting how many 7's there are, but if I were to input 753 as a number, it would not count the 7 from the 753. How would I include that? Would it require a whole rewrite?

CodePudding user response:

In C, '7' is the character representing seven, which is not the same as the value 7 (in ASCII, for example, '7' is 55).

Hence you should use 7 for the comparison, rather than '7':

if (array[i] == 7)
  • Related