Calculator Program in C using do while loop and switch statement.
#include <stdio.h>#include <math.h>
#include <stdlib.h>
int main()
{
// declaration of local variable;
int task, n1, n2;
float res;
char ch;
do
{
// displays the multiple operations of the C Calculator
printf (" Select an operation to perform the calculation in C Calculator: ");
printf (" \n 1 Addition \t \t 2 Subtraction \n 3 Multiplication \t 4 Division \n 5 Square \t \t 6 Square Root \n 7 Exit \n \n Please, Make a choice ");
scanf ("%d", &task); //it accepts a numeric input to choose the operation
//it use switch statement to call an operation
switch (task)
{
case 1:
//it is used to add two numbers
printf (" You chose: Addition");
printf ("\n Enter First Number: ");
scanf (" %d", &n1);
printf (" Enter Second Number: ");
scanf (" %d", &n2);
res = n1 + n2; // Add two numbers
printf (" Addition of two numbers is: %.2f", res);
break; // break the function
case 2:
//it is used to subtract two numbers
printf (" You chose: Subtraction");
printf ("\n Enter First Number: ");
scanf (" %d", &n1);
printf (" Enter Second Number: ");
scanf (" %d", &n2);
res = n1 - n2; // subtract two numbers
printf (" Subtraction of two numbers is: %.2f", res);
break; // break the function
case 3:
//it is used to multiplication of the numbers
printf (" You chose: Multiplication");
printf ("\n Enter First Number: ");
scanf (" %d", &n1);
printf (" Enter Second Number: ");
scanf (" %d", &n2);
res = n1 * n2; // multiply two numbers
printf (" Multiplication of two numbers is: %.2f", res);
break; // break the function
case 4:
//it is used to division of the numbers
printf (" You chose: Division");
printf ("\n Enter First Number: ");
scanf (" %d", &n1);
printf (" Enter Second Number: ");
scanf (" %d", &n2);
if (n2 == 0)
{
printf (" \n Divisor cannot be zero. Please enter another value ");
scanf ("%d", &n2);
}
res = n1 / n2; // divide two numbers
printf (" Division of two numbers is: %.2f", res);
break; // break the function
case 5:
//it is used to get square of a number
printf (" You chose: Square");
printf ("\n Enter First Number: ");
scanf (" %d", &n1);
res = n1 * n1; // get square of a number
printf (" Square of %d number is: %.2f", n1, res);
break; // break the function
case 6:
//it is used to get the square root of the number
printf (" You chose: Square Root");
printf ("\n Enter First Number: ");
scanf (" %d", &n1);
res = sqrt(n1); // use sqrt() function to find the Square Root
printf (" Square Root of %d numbers is: %.2f", n1, res);
break; // break the function
case 7:
printf (" You chose: Exit");
exit(0);
break; // break the function
default:
printf(" Something is wrong!! ");
break;
}
printf (" \n \n ********************************************** \n ");
} while (task != 7);
return 0;
}
Calculator in C |
Expected Output:-
Output |
Tags:
C Program to make a calculator using while loop and switch statement
calculator using while and switch
mskuthar