Program for Simple Calculator

Beginner

Introduction

In this lab, we will be creating a simple calculator program using C++. This program will use switch statements to perform basic arithmetic operations such as addition, subtraction, multiplication and division.

Set up the program file

First, we need to create the main.cpp file in the ~/project directory. Use your favorite text editor to create a new file named main.cpp.

touch ~/project/main.cpp

Include necessary libraries

In the main.cpp file, we need to include the iostream header file.

#include <iostream>

Add the main function

Next, we need to add the main function to our program.

int main() {
    // Code goes here
    return 0;
}

Declare variables and ask for user input

In the main function, we need to declare the necessary variables and ask the user for input.

int main() {
    char op;
    float num1, num2;

    std::cout << "Enter operator either + or - or * or /: ";
    std::cin >> op;

    std::cout << "\nEnter two operands: ";
    std::cin >> num1 >> num2;

    // Code goes here

    return 0;
}

Add switch statement

We can use a switch statement to perform the necessary operation based on the operator entered by the user.

int main() {
    char op;
    float num1, num2;

    std::cout << "Enter operator either + or - or * or /: ";
    std::cin >> op;

    std::cout << "\nEnter two operands: ";
    std::cin >> num1 >> num2;

    switch(op) {
        case '+':
            std::cout << "\nResult is: " << num1 + num2;
            break;

        case '-':
            std::cout << "\nResult is: " << num1 - num2;
            break;

        case '*':
            std::cout << "\nResult is: " << num1 * num2;
            break;

        case '/':
            std::cout << "\nResult is: " << num1 / num2;
            break;

        default:
            // If the operator is other than +, -, * or /, error message is shown
            std::cout << "Error! operator is not correct";
            break;
    }

    return 0;
}

Compile and run the program

Compile the program using the following command in the terminal of Ubuntu system:

g++ ~/project/main.cpp -o main && ./main

Summary

In this lab, we created a simple calculator program using C++. We used switch statements to perform basic arithmetic operations based on user input. By following the steps outlined in this lab, you should now have a working knowledge of how to create a basic calculator program in C++.

Other Tutorials you may like