Build a Sleek Calculator with Modular Functions

functions. Master the basics of programming while creating a functional tool for arithmetic operations."> Build a Sleek Calculator with Modular Functions

Build a Sleek Calculator with Modular Functions

Welcome to this step-by-step guide on creating a simple yet powerful calculator program in C++ using functions. If you're looking to enhance your coding skills and make your programs more modular and reusable, this tutorial is for you!

How to Make the Calculator

First, let's set up our basic program structure. We'll include necessary headers, declare our functions, and write the main function to handle user input and call the appropriate function based on the user's choice.

Here's the initial code setup:


#include <iostream>
#include <stdlib.h>
using namespace std;

void addition(int x, int y);
void subtraction(int x, int y);
void multiplication(int x, int y);
void division(int x, int y);

int main() {
    int a, b, choice;
    cout << "\n";
    cout << "1. Addition\n";
    cout << "2. Subtraction\n";
    cout << "3. Multiplication\n";
    cout << "4. Division\n";
    cout << "5. Exit\n";

    cout << "Enter your choice: ";
    cin >> choice;
    cout << "\nYour Choice is " << choice << ".\n";

    cout << "Enter first number: ";
    cin >> a;
    cout << "Enter second number: ";
    cin >> b;

    if (choice == 1)
        addition(a, b);
    else if (choice == 2)
        subtraction(a, b);
    else if (choice == 3)
        multiplication(a, b);
    else if (choice == 4)
        division(a, b);
    else
        cout << "Invalid Operation!!!";
}
    

Functions

Next, we need to define the functions that will perform the arithmetic operations. Each function will take two integers as parameters and output the result of the corresponding operation.

Here are the function definitions:


void addition(int x, int y) {
    cout << "Addition of 'a' and 'b' is " << x + y << ".";
}

void subtraction(int x, int y) {
    cout << "Subtraction of 'a' and 'b' is " << x - y << ".";
}

void multiplication(int x, int y) {
    cout << "Multiplication of 'a' and 'b' is " << x * y << ".";
}

void division(int x, int y) {
    cout << "Division of 'a' and 'b' is " << (float)x / y << ".";
}
    

Here's the full Code


Output

When you run the program, it will display a menu for selecting the operation and prompt you to enter two numbers. Here's an example of the output:

By modularizing the code into separate functions for each arithmetic operation, we make the program more organized and easier to maintain. This approach also demonstrates the power of functions in making code reusable and easier to read. Try adding more features or operations to this calculator as an exercise to further enhance your programming skills!

Post a Comment

0 Comments