Start by defining a function for each arithmetic operation. This modular approach helps in maintaining and understanding the code easily.
#include <stdio.h> double add(double a, double b) { return a + b; } double subtract(double a, double b) { return a - b; } double multiply(double a, double b) { return a * b; } double divide(double a, double b) { return b != 0 ? a / b : 0.0; } int main() { double num1, num2; char operator; printf("Enter an operation (+, -, *, /): "); scanf("%c", &operator); printf("Enter two numbers: "); scanf("%lf %lf", &num1, &num2); switch(operator) { case '+': printf("Result: %.2lf", add(num1, num2)); break; case '-': printf("Result: %.2lf", subtract(num1, num2)); break; case '*': printf("Result: %.2lf", multiply(num1, num2)); break; case '/': printf("Result: %.2lf", divide(num1, num2)); break; default: printf("Invalid operation!"); } return 0; }
This program asks the user for an operation and two numbers, then calculates the result based on the operation using a switch-case statement.