SH Codegner
SH Codegner

Reputation: 3

Arrays and initializing more than one counter

#include <stdio.h>
int main() {
    int niz[100], i, j, k, l;
    j = 0; // k=l=0;
    printf("Unesite niz (-1 for end)");
    do {
        scanf("%d", &niz[i]);
        if (niz[i] % 5 == 0)
            j++;
        // if(niz[i]%7==0) k++;
        // if(niz[i]%11==0) l++;
    } while (niz[i] != -1);
    printf("Broj djeljivih sa 5 je:%d", j);
    // printf("Broj djeljivih sa 7 je:%d",k);
    // printf("Broj djeljivih sa 11 je:%d",l);
    return (0);
}

What's problem with this code, it works fine with comments but when I uncheck comments it gives me a crash. The problem I have is to solve how much numbers are possible to divide by 5,7 and 11.

Upvotes: 0

Views: 73

Answers (2)

Abhishek Choubey
Abhishek Choubey

Reputation: 883

Since all the variables i, j, k,l are automatic(storage class) integers, by default such variables will have indeterminate (an unspecified value or a trap representation ) value. There fore you need to initialise the variable explicitly.

Moreover, In the code, you are not incrementing the value of "i", then what is the point of using the array. All the input numbers will be stored at niz[i](where "i" may or not be a valid index), thus every new input will overwrite the previous one.

I found the following link to be very useful with respect to your problem.

http://stackoverflow.com/questions/6212921/is-un-initialized-integer-always-default-to-0-in-c

Upvotes: 0

Yogeesh Seralathan
Yogeesh Seralathan

Reputation: 1414

Garbage value @ variable i. So you are trying to reach unindexed part of the array.

  1. Initialize i = 0;

  2. Make sure your loops ends before it again reaches end the array.

    do { // Whatever you want to do } while(niz[i]!=-1 && i<100);// Add 1 more condition for i less than 100

Upvotes: 1

Related Questions