In this lesson, we will learn C++ Program to Make a Simple Mathematical calculator by using switch statements. First, we define the switch structure and see the syntax of the switch structure of the c/c++ language.

C++ Program to Make a Simple Mathematical calculator

The definition and syntax of switch structure are as follows
You can copy and make a source file compiler
To understand the example you must have knowledge about the Syntax of the case statements and the basic structure of c++.
This program takes an arithmetic operator (+, -, *, /) and two operands from the user and performs the operation on those two operands depending upon the operator.

# include <iostream.h>
#include <conio.h>
void main()
{
    char op;
    float n1, n2;
    cout << "Enter operator  + or - or * or /: ";
    cin >> op;
    cout << "Enter two operands: ";
    cin >> n1 >> n2;
    switch(op)
    {
        case '+':
            cout << n1+n2;
            break;
        case '-':
            cout << n1-n2;
            break;
        case '*':
            cout << n1*2;
            break;
        case '/':
            cout << n1/n2;
            break;
         case '/':
            cout << n1%n2;
            break;
        default:
            cout << "wrong oprater plz inter +,-,*,/ or %";
            break;
    }
 getch();
}

C program for a simple calculator

C++ and c have almost the same structure but only some differences

  1. In c++ prepossess directive iostream.h is used for including stranded input-output functions  while in c language stdio.h is used
  2. For output, cout is used in c++ while in c language printf  is used for output
  3. In C++ cin is used for getting input from the user while in c coding scanf function is used for getting input from the user.
  4. In c++ format specifier are not used to print output and for getting input while format specifiers are used in c coding.
# include <stdio.h>
 #include <conio.h>
void main()
{
clrscr();
    char op;
    float n1, n2;
    printf( "Enter operator  + or - or * or /: ");
    scanf("%c",op);
    printf( "Enter two operands: ");
    scanf("%f %f",&n1,&n2);
    switch(op)
    {
        case '+':
            printf("%f", n1+n2);
            break;
        case '-':
            printf("%f", n1-n2);
            break;
        case '*':
            printf("%f", n1*n2);
            break;
        case '/':
             printf("%f", n1/n2);
            break;
         case '%':
             printf("%f", n1%n2);
             break;
        default:
            printf("wrong oprater plz inter +,-,*,/ or %");
            break;
    }
 getch();
}
Advertisements
Advertisements
Advertisements