google.com, pub-4617457846989927, DIRECT, f08c47fec0942fa0 Learn to enjoy every minute of your life.Only I can change my life.: Write a C program to create a calculator that performs basic arithmetic operations

Sunday, March 2, 2025

Write a C program to create a calculator that performs basic arithmetic operations

 Here is a simple C program to create a calculator that performs basic arithmetic operations:


#include <stdio.h>


void printMenu() {

    printf("Simple Calculator\n");

    printf("1. Addition\n");

    printf("2. Subtraction\n");

    printf("3. Multiplication\n");

    printf("4. Division\n");

    printf("5. Exit\n");

}


int main() {

    int choice;

    float num1, num2, result;


    while (1) {

        printMenu();

        printf("Enter your choice: ");

        scanf("%d", &choice);


        if (choice == 5) {

            printf("Exiting the calculator. Goodbye!\n");

            break;

        }


        printf("Enter the first number: ");

        scanf("%f", &num1);


        printf("Enter the second number: ");

        scanf("%f", &num2);


        switch (choice) {

            case 1:

                result = num1 + num2;

                printf("%.2f + %.2f = %.2f\n", num1, num2, result);

                break;

            case 2:

                result = num1 - num2;

                printf("%.2f - %.2f = %.2f\n", num1, num2, result);

                break;

            case 3:

                result = num1 * num2;

                printf("%.2f * %.2f = %.2f\n", num1, num2, result);

                break;

            case 4:

                if (num2 != 0) {

                    result = num1 / num2;

                    printf("%.2f / %.2f = %.2f\n", num1, num2, result);

                } else {

                    printf("Error! Division by zero is not allowed.\n");

                }

                break;

            default:

                printf("Invalid choice. Please choose a valid option.\n");

        }

    }


    return 0;

}

```


*Example Use Cases:*

1. Run the program and select option 1 (Addition).

2. Enter two numbers, e.g., 10 and 20.

3. The program will display the result: 10.00 + 20.00 = 30.00.

4. Repeat the process for other arithmetic operations.


*How to Compile and Run:*

1. Save the code in a file named `calculator.c`.

2. Open a terminal or command prompt.

3. Navigate to the directory where you saved the file.

4. Compile the program using `gcc calculator.c -o calculator`.

5. Run the program using `./calculator` (on Linux/macOS) or `calculator.exe` (on Windows).

No comments:

Post a Comment

simple C++ program to manage a kirana store

 Here's a simple C++ program to manage a kirana store: #include <iostream> #include <string> #include <map> using name...