POP Lab Manual

Program 1

Develop a program to simulate a Simple Calculator that performs basic arithmetic operations including addition, subtraction, multiplication, and division with proper error handling for division by zero.
Supported Operations:
Addition: a + b
Subtraction: a - b
Multiplication: a * b
Division: a / b (with zero check)

Algorithm

  1. Initialize: Start the program
  2. Input Operator: Read operator (+, -, *, /) from user
  3. Input Numbers: Read two double numbers (a, b) from user
  4. Process Operation: Use switch case to perform selected operation
  5. Check Division: For division, verify b ≠ 0 to prevent error
  6. Calculate Result: Perform the arithmetic operation
  7. Output: Display the result or error message
  8. Terminate: Stop the program

Flowchart

START
Input op
Input a, b
Switch(op)
Calculate & Display
STOP

Code

#include <stdio.h>


int main() {
    char op;
    double a, b;

    // Prompt user for operator
    printf("Enter an operator (+, -, *, /): ");
    scanf("%c", &op);

    // Prompt user for two numbers
    printf("Enter two numbers: ");
    scanf("%lf %lf", &a, &b);

    // Perform calculation based on operator
    switch(op) {
        case '+': 
            printf("Result = %.2lf\n", a + b); 
            break;
        case '-': 
            printf("Result = %.2lf\n", a - b); 
            break;
        case '*': 
            printf("Result = %.2lf\n", a * b); 
            break;
        case '/': 
            if(b != 0) 
                printf("Result = %.2lf\n", a / b);
            else 
                printf("Error! Division by zero.\n");
            break;
        default: 
            printf("Invalid operator!\n");
    }

    return 0;
}

Output


// Output 1 - Addition
Enter an operator (+, -, *, /): +
Enter two numbers: 15.5 10.3
Result = 25.80

// Output 2 - Multiplication  
Enter an operator (+, -, *, /): *
Enter two numbers: 7.5 4.0
Result = 30.00

// Output 3 - Division
Enter an operator (+, -, *, /): /
Enter two numbers: 20.0 4.0
Result = 5.00

// Output 4 - Division by Zero Error
Enter an operator (+, -, *, /): /
Enter two numbers: 10.0 0.0
Error! Division by zero.

// Output 5 - Invalid Operator
Enter an operator (+, -, *, /): %
Enter two numbers: 8.0 3.0
Invalid operator!
          
Comments

Replay !

0 Comments

Share Your Thoughts

Please enter your name
Please enter a valid email
Password must be at least 6 characters
Please enter your comment
Email Verification Required
We've sent a 6-digit verification code to . Please enter the code below to verify your email address.
Email Verified Successfully!
Your email has been verified. Would you like to proceed with posting your comment?

Type "YES" to confirm and post your comment, or click Cancel to skip posting.