Ghislo
Ghislo

Reputation: 85

while loop exiting without condition false

I don't understand why this code breaks the loop when tot is equal or less than 10 and it doesn't when it is more than 10.

I can't believe I still can't manage this basic thing.. help me please!

do {
    tot = 0;
    system("CLS");

    printf("Inserisci 10 sfere tra rosse, blu e verdi");

    printf("\n\n Rosse : ");
    scanf(" %d" , &rosse);  
    tot += rosse;   
    for (i = 0; i < rosse; i++) {
        sfere[i] = 1;
    }

    printf("\n Verdi : ");
    scanf(" %d", &verdi);
    tot += verdi;
    for (i = 0; i < verdi; i++) {
        sfere[i+rosse] = 2;
    }

    printf("\n Blu : ");
    scanf(" %d", &blu);
    tot += blu;
    for (i = 0; i < blu; i++) {
        sfere[i+rosse+verdi] = 3;
    }       

    if (tot == 10) {
        break;
    }
}   while (true);

I tried as well doing it like this but i get the same result..

while (tot != 10);

I underline that i am using scanf and printf because my university course wants to, to make us understand better how the memory works and keep safe from errors in future.

Upvotes: 0

Views: 111

Answers (4)

Ghislo
Ghislo

Reputation: 85

I solved it! i don't know why my loop was never ending because of some code outside the loop.. It began working when i changed srand(time(NULL)) with srand(time(&t)) !!! (declaring time_t t; before.

Upvotes: 0

Zainegardner
Zainegardner

Reputation: 11

You're tot variable is getting arbitrary numbers. It would probably be better to do:

if(tot >= 10){
     break
}

Unless there is a specific reason that you think tot will always be 10. Otherwise, you've got an infinite loop if tot doesn't end up being 10.

An alternative, which would leverage a do{}while() loop would be to do:

 do{
      //code
 }while(tot >= 10)

Upvotes: 1

Weather Vane
Weather Vane

Reputation: 34575

Change this

    // ...
    if (tot == 10) {
        break;
    }
} while (true);

to this

   // ...
} while (tot < 10);

because the total might not hit exactly 10, and because the logic is cleaner and sweeter - notice how I use your required condition to end the loop.

Upvotes: 0

Keammoort
Keammoort

Reputation: 3075

The code you provided will only break a while loop when tot is equal to 10

if (tot == 10) {
    break;
}

The second snippet (the one below) will behave the same however this approach is better since you're explicitely writing the loop should end when tot equals 10 (then condition tot != 10 will become false which will stop the loop):

while (tot != 10);

Upvotes: 1

Related Questions