Javaria Shah
Javaria Shah

Reputation: 1

number of elements in an array

can anyone help me how to print the number of results calculated by a loop? this is my code:

#include <stdio.h>
int
main (void)

{

    int monthly_water_arr[30];
    int x,num_months;
    int count_0=0;
    FILE *in;
    in = fopen("water.txt","r");
    x=0;
    while (!feof(in))
    {
        fscanf(in,"%d",&monthly_water_arr[x]);
        x++;
        ;
    }
    printf("count is %d\n", count_0);
    printf(" Numbers read from file are:\n");
    for (x=0;x<30;x++){
        printf("%d\n",monthly_water_arr[x]);
    }
    num_months = sizeof(monthly_water_arr)/ sizeof(monthly_water_arr[0]);
    printf("The number of months in file are: %d\n",num_months);
    for (x=0;x<30;x++){
        if(monthly_water_arr[x]>=71 && monthly_water_arr[x]<=80);
        count_0=count_0+1
    }

            return (0);
}

the count_0 is supposed to give two, but i've tried alot and there are actually just 2 numbers between 71 and 80 and everytime i just get 30

Upvotes: 0

Views: 50

Answers (1)

Vitruvie
Vitruvie

Reputation: 2327

You misplaced a semicolon:

if(monthly_water_arr[x]>=71 && monthly_water_arr[x]<=80);
count_0=count_0+1

Note the semicolon after the if. This would really be more accurately written as:

if(monthly_water_arr[x]>=71 && monthly_water_arr[x]<=80) //If this,
    ; //Do nothing.
count_0=count_0+1 //Either way, increment count.

Do not place semicolons after if, for, or while statements. Remove it so that the count increment is inside the if:

if(monthly_water_arr[x]>=71 && monthly_water_arr[x]<=80)
    count_0=count_0+1; //or, more concisely, ++count_0;

Upvotes: 3

Related Questions