Reputation: 43
The loop works perfectly fine until the exit condition is entered, instead of exiting once 12345 is entered, the next statement in the loop executes. I've tried putting the first statement outside of the loop, putting just the calculations in the loop.
It just ignores the condition.
This is the code
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
int firstValue, pointsReceived;
while(firstValue != 12345){
NSLog(@"Enter the total points available (enter 12345 to stop program):\n");
scanf("%i", &firstValue);
NSLog(@"Enter the total points received: \n");
scanf("%i", &pointsReceived);
float percentage = (100 * pointsReceived) / firstValue;
NSLog(@"Your total percentage is: %.2f%%", percentage);
if(percentage >= 90){
NSLog(@"Your grade is an A");
}
else if(percentage >= 80){
NSLog(@"Your grade is a B");
}
else if(percentage >= 70){
NSLog(@"Your grade is a C");
}
else if(percentage >= 60){
NSLog(@"Your grade is a D");
}
else{
NSLog(@"Your grade is an F");
}
}
NSLog(@"Done!");
}
return 0;
}
Upvotes: 0
Views: 489
Reputation: 536
while loop only checks the if condition at the end of the loop. if the user entered 12345 at the first scanf the loop will still execute, you will need to write another if statement after the scanf
if (firstValue == 12345)
{
break;
}
Upvotes: 0
Reputation: 494
See here for an explanation of while loops in Objective-C.
What's happening in your code is that everything inside the 'while' block is computed before the condition is verified, therefore even if the user types "12345", it still continues running the code inside the loop before checking for the condition.
One simple solution is to add an 'if' statement checking for the condition right after receiving the user input.
if (firstValue == 12345) break;
Upvotes: 1