do while loops c

do while loops c  using -'c'

I know this is a probably a very simple question but i've asked a few experienced people and they can't figure it out and they don't know why. It's just a simple do while loop thats actually straight out of a book "absolute beginners guide to c". when it runs and you type n for entering more numbers it keeps running, how do you get it to exit the loop. im using xcode on mac and its using C. tried it on the vmfusion complier they use for harvards cs50 as well and it doesn't work either.

#include <stdio.h>

int main() {
float num1, num2, result;
char choice;
do {
    num1 = num2 = result = 0;
    printf("first number?\n");
    scanf(" %f", &num1);
    printf("second number?\n");
    scanf(" %f", &num2);
    result = num1*num2;
    printf("ans = %.0f\n", result);
    printf("do you want to enter another pair of numbers? (Y/N)\n");
    scanf(" %c", &choice);

} while (choice != 'N' && choice  != '\n');
return 0;


asked Sep 9, 2015 by ValBumgarne
0 votes

2 Answers

0 votes

It will stop running if you type N ('N') or Enter ('\n'). If you want to stop it typing a lowercase n ('n') too, you should write:

while (choice != 'N' && choice != 'n' && choice  != '\n');
answered Sep 9, 2015 by GeorgiannMcL
0 votes
scanf(" %f", &num1);

should be

scanf("%f", &num1);

and check the return value of scanf()

if(scanf("%f", &num1) != 1)
  printf("scanf failed\n");

When you enter N or \n you should be able to exit the loop after this

answered Sep 9, 2015 by MaeVmpwphnu