Home > Blockchain >  How to use while loops properly?
How to use while loops properly?

Time:09-24

I'm a beginner in programming and here you could see that this program will get ask the user to input their grade from their first to third periodic, which will then display the average. Everything was going fine not until I get to the part where the user will be asked if he would like to average another set, when I type y(yes) it'll loop the whole thing again and again starting from the "your average grade is..". To me, I think the problem was about my bad looping. Why did that loop only that line and not the whole program? Any way I could improve my looping and programming? Is there anyway I could shorten this program?

Thanks for the time you gave answering this question.

#include <iostream>
#include <string>
using std::cout, std::cin, std::string,std::endl;
int main() {
  char again{};
  double P1{}, P2{}, P3{}, Grade{}, Result{};
string phrase  {"Your average grade is "},
       phrase1 {"Error! number should be in range of (1 to 100)."},
       result1 {"Failed"},
       result2 {"Study Harder"}, 
       result3 {"Job well done"}, 
       result4 {"Very good student"}, 
       result5 {"Exceptional student"};

cout<<"Enter your P1 grade: ";
cin>> P1;
cout<<"Enter your P2 grade: ";
cin>> P2;
cout<<"Enter your P3 grade: ";
cin>> P3; 
cout<<"\n";
while(P1 > 100 || P1 <= 0){
  cout << phrase1  << endl;
       cout << "Enter the Your P1 grade again: ";
          cin>> P1;}
while(P2 > 100 || P2 <= 0){ 
   cout << phrase1  << endl;
       cout << "Enter the Your P2 grade again: ";
          cin>> P2;}
 while(P3 > 100 || P3 <= 0){ 
   cout << phrase1  << endl;
       cout << "Enter the Your P3 grade again: ";
          cin>> P3;
          cout<<"\n";}
do{
Result = P1 * 0.33   P2 *0.33   P3 *0.34;
if (Result <= 49)
  cout<< phrase << Result << ", " << result1<<endl;
if (Result >= 50 && Result <= 70)
  cout<< phrase << Result << ", " << result2<<endl;
if (Result >= 71 && Result <= 80)
  cout<< phrase << Result << ", " << result3<<endl;
if (Result >= 81 && Result <= 90)
  cout<< phrase << Result << ", " << result4<<endl;
if (Result >= 91 && Result <= 100)
  cout<< phrase << Result << ", " << result5<<endl;
 cout<<"Would you like to average another set?(Y/N) ";
 cin>>again;
 cout<<"\n";
}while(toupper(again) =='Y' );//asks if the user would like to do another set 
return 0;
}

The Error

CodePudding user response:

When your while loop is triggered, it goes back to do statement and executes the program from there.

Now the problem is that the value in the do scope doesn't get updated because you are not giving input again.

The simple solution I believe is that you should move your do statement to the top.

do {
    cout << "Enter your P1 grade: ";
    // rest of the code here...
}
  •  Tags:  
  • c
  • Related