0
#include<stdio.h>
void main(){
    char choice1,choice2;
    int a,b,c;
    while(choice1 != 'n'){
        printf("Enter + for addition:\n");
        printf("Enter - for substraction:\n");
        printf("Enter * for multiplication:\n");
        printf("Enter / for division:\n");
        scanf("%c",&choice2);
        printf("Enter two numbers:\n");
        scanf("%d %d",&a,&b);
        if (choice2 == '+'){
            c=a+b;
            printf("Addition = %d",c);
        }
        else if (choice2 == '-'){
            c=a-b;
            printf("Substraction = %d",c);
        }
        else if (choice2 == '*'){
            c=a*b;
            printf("Multiplication = %d",c);
        }
        else if (choice2 == '/'){
            c=a/b;
            printf("Division = %d",c);
        }
        else{
            printf("Invalid choice!");
        }
        printf("\nEnter y to continue and n to exit:\n ");
        scanf("%c",&choice1);
    }
}

When I run the above program, the while loop repeats without taking the value of choice1 from the user. Can anyone please tell me what is wrong in the above code???

5
  • Start with a simpler loop and work up, don't write something this complicated and then wonder why it breaks. Commented Feb 16, 2015 at 15:18
  • use do while instead of while. Commented Feb 16, 2015 at 15:19
  • while(choice1 != 'n') first time around, choice1 is uninitialized, so you have undefined behaviour. Commented Feb 16, 2015 at 15:20
  • And add a check to prevent division by 0. Commented Feb 16, 2015 at 15:23
  • choice1 is being set as the newline character you haven't collected after the last scanf() call. Commented Feb 16, 2015 at 15:28

2 Answers 2

3

choice1 is compared without initializing in the expression choice1 != 'n'. Use do while loop instead or change it as follows

scanf(" %c",&choice1);
while(choice1 != 'n'){  
     // Loop body

      scanf(" %c",&choice1); // Do not forget to add a space before %c to skip newline 
                             //characters left behind by previous call to scanf.
}
Sign up to request clarification or add additional context in comments.

Comments

1

well yes choice1 is uninitialized and you are also ignoring the return values of your scans.

But to answer YOUR question. Your problem is that choice1 gets the value '\n' after scanning not 'n' as you might think, because '\n' is before 'n' in the buffer,

so use getchar() before you scan for choice1 at the end, and it will work.

I mean do this:

getchar();

scanf("%c", &choice1);

1 Comment

more usual approach is scanf(" %c", &choice1);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.