Home > Enterprise >  'Repeating calculator' program in C with swtich case and do while loop, not working after
'Repeating calculator' program in C with swtich case and do while loop, not working after

Time:12-15

#include <stdio.h>
int main()
{
    char operator;
    double num1, num2, sum, mult, div, subtract, percentage;
    

    do
    {
        printf("Enter a operator :\n");
        printf("Click ' ' for Addition\n");
        printf("Click '-' for Subtraction\n");
        printf("Click '*' for Multiplication\n");
        printf("Click '/' for Division\n");
        printf("Click '%%' for Percentage\n");
        printf("Click '0' for Exit\n");
        scanf("%c", &operator);
        printf("Enter any two numbers\n");
        scanf("%lf%lf", &num1, &num2);

        switch (operator)
        {
        case (' '):
            sum = num1   num2;
            printf("The sum of %.2lf and %.2lf is %.2lf\n", num1, num2, sum);
            break;
        case ('-'):
            subtract = num1 - num2;
            printf("The substraction of %.2lf and %.2lf is %.2lf\n", num1, num2, subtract);
            break;
        case ('*'):
            mult = num1   num2;
            printf("The multiplication of %.2lf and %.2lf is %.2lf\n", num1, num2, mult);
            break;
        case ('/'):
            div = num1 / num2;
            printf("The division of %.2lf and %.2lf is %.2lf\n", num1, num2, div);
            break;
        case ('%'):
            percentage = (num1 / num2) * 100;
            printf("The percentage of %.2lf and %.2lf is %.2lf %%\n", num1, num2, percentage);
            break;
        default:
            printf("Invalid number, try a valid number\n");
        }
    } while (operator!= '0');

    return 0;
}

What did I try?

  • I am trying to make a repeating calculator program using switch case and do while loop (for repeating the same program.)

What am I expecting?

  • I am expecting the calculator to repeat and ask the user whether the user wants to continue using the calculator or not.

What in reality is happening?

  • At 1st compilation, everything works properly and the calculator runs. But, during the second compilation, the program is not scanning 'operator' and directly jumping to 'enter the numbers'.

CodePudding user response:

As already answered by Johnny Mopp and Andreas Wenzel, your scanf("%c", &operator); call reads the newline (\n) from the scanf("%lf%lf", &num1, &num2); that ran in the previous iteration of the loop.

You can change the call to include a space before the %c specifier in the format string to allow the scanf() function to skip any leading whitespace characters in the input buffer.

It should look like the following:

scanf(" %c", &operator);

Additionally, in your multiplication calculation, you used the operator instead of *.

  • Related