Amar Pawar
Amar Pawar

Reputation: 177

Repeat while loop according to the user input

#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???

Upvotes: 0

Views: 807

Answers (2)

Gravity
Gravity

Reputation: 311

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);

Upvotes: 1

haccks
haccks

Reputation: 106002

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.
}

Upvotes: 3

Related Questions