#include<stdio.h>intmain() {char operator;double num1, num2;int keepGoing =1; // flag to keep the loop goingwhile (keepGoing) {// Ask the user to enter an operatorprintf("Enter an operator (+, -, *, /): ");scanf("%c", &operator);// Ask the user to enter two operandsprintf("Enter two operands: ");scanf("%lf%lf", &num1, &num2);switch (operator) {case'+':printf("%.2lf + %.2lf = %.2lf\n", num1, num2, num1 + num2);break;case'-':printf("%.2lf - %.2lf = %.2lf\n", num1, num2, num1 - num2);break;case'*':printf("%.2lf * %.2lf = %.2lf\n", num1, num2, num1 *num2);break;case'/':if (num2 !=0.0)printf("%.2lf / %.2lf = %.2lf\n", num1, num2, num1 / num2);elseprintf("Error! Division by zero.\n");break;default:printf("Error! Operator is not correct.\n"); }// Ask the user if they want to continue or exitchar choice;printf("Do you want to perform another calculation? (y/n): ");scanf("%c", &choice);if (choice =='n'|| choice =='N') { keepGoing =0; } }printf("Calculator exited.\n");return0;}
Explanation:
Initialization: We declare the variables needed for the calculator: operator, num1, num2, and keepGoing.
Loop: The while loop runs as long as keepGoing is 1.
Input: Inside the loop, we prompt the user to enter an operator and two operands.
Switch Statement: Based on the entered operator, the appropriate arithmetic operation is performed and the result is displayed.
Continue or Exit: After performing the calculation, the user is asked if they want to perform another calculation or exit. If the user enters 'n' or 'N', the loop ends and the program exits.
Exit Message: When the loop ends, a message is displayed indicating that the calculator has exited.