How do I get the C program Loop/s to exit with a user input \"increment\" of \'0
ID: 3721922 • Letter: H
Question
How do I get the C program Loop/s to exit with a user input "increment" of '0'? My "while (increment!= 0)" styntax (or design) isn't working and the program currently runs in an infinite loop with zero 'increment'.
#include
int main()
{
float ivalue= 1;
float increment = 1;
float fvalue = 1;
float MilesPrHr;
float RodsPerMinute ;
float FrlngsFrtnight;
float SmootSeconds ;
while (increment!= 0){ //THIS not operator isn't functioning
printf("Enter initial value ");
scanf("%f", &MilesPrHr);
printf("Enter final value ");
scanf("%f", &fvalue);
printf("Enter increment value ");
scanf("%f", &increment);
for (MilesPrHr =ivalue; MilesPrHr<= fvalue; MilesPrHr = MilesPrHr + increment){
RodsPerMinute = MilesPrHr*5.33333 ;
FrlngsFrtnight= MilesPrHr*2687.99 ;
SmootSeconds= MilesPrHr*.2626867 ;
printf(" miles/hr rods/min frlngs/frtnght Smoots/sec ");
printf(" %f ", MilesPrHr );
printf("%f ", RodsPerMinute);
printf("%f ", FrlngsFrtnight);
printf("%f ", SmootSeconds);}
}
}
Explanation / Answer
Here,
The problem is not with your "while(increment!= 0)" loop but your inner loop,
i.e " for (MilesPrHr =ivalue; MilesPrHr<= fvalue; MilesPrHr = MilesPrHr + increment)" loop.
"while" loop checks the value of increment at the start of the while<body>. So since you change the value of the 'increment' to '0' somewhere in the body of the while loop, it will still run once until it reiterates back to while(condition) and stop the loop.
But, there is also the other loop, which is the for loop. And, you increment the for loop variable using "increment" itself. So, if u put "increment" as 0, the for loop variables doesnt get incremented and it gets struck in an infinite loop.
Hint: if u want to stop the loop on increment = 0, u can use break statement.Eg.
After scanning the increment,
if(increment==0)
break; // It will break exit the loop.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.