Home > OS >  While loop logic not working on my code, cant figure it out
While loop logic not working on my code, cant figure it out

Time:01-21

Im having issues on how to make the while loop work on my code (C ), can you please help? I want the user to be asked a question and if the answer is "si" then to execute what I have for the if statements. If answer is no, then skip the while loop and execute the last code. Im getting an error after all the input, just an endless loop of letters. Any hints on how I can fix it will be very appreciated! Thank you.

int main()
{   
    int a, b, c, d, total, promedio;
    
    string siNo;

    
    cout << "Ingresar nota 1: ";
    cin >> a;
    cout <<"Ingrese segunda nota: ";
    cin >> b;
    cout << "Ingrese tercera nota: ";
    cin >> c;
    cout << "Ingresar nota 4: ";
    cin >> d;

    cout<<endl;

    cout << "Desea eximirse? ";
    cin >> siNo;

    total = (a b c d)/4;
    promedio = (a b c)/3;

    while (siNo != "no"){

    if(promedio >= 85){
        cout << "Si está eximido, su promedio es: "   promedio;
    }
    if(promedio < 85){
        cout << "No está eximido, su promedio de los 3 parciales es:"   promedio;
        }

    }
    
    cout << "Su nota final es "   total;
    
     return 0;
}

CodePudding user response:

You haven't given any exit loop statement inside your while loop that is why it is running in infinite loop

while (siNo != "no"){
    if(promedio >= 85){
        cout << "Si está eximido, su promedio es: "   promedio;
        break; // just add this line
    }
    if(promedio < 85){
        cout << "No está eximido, su promedio de los 3 parciales es:"   promedio;
        break;
    }
}

CodePudding user response:

This is an infinite loop:

while (siNo != "no") {

    if(promedio >= 85){
        cout << "Si está eximido, su promedio es: "   promedio;
    }
    if(promedio < 85) {
        cout << "No está eximido, su promedio de los 3 parciales es:"   promedio;
    }
}

Since nothing changes siNo after the cout statements, it's going to keep evaluating (siNo != "no") to be true.

CodePudding user response:

I don't think a loop is necessary here

// if answer is equal to "si"
if (siNo == "si") { 
   if(promedio >= 85){ 
   } // continue here
} 

// else is not required 
// if you don't want to do anything when answer is no

return 0;

A simple if statement will do the trick for ya.

  •  Tags:  
  • Related