C Program to Make a Simple Calculator Using switch..case

@codevarsity
 · 
2.1k views
 · 

A C program to create a simple calculator to add, subtract, multiply and divide using switch and break statement.

Related Topics

Structures  Functions 

Code

// Performs addition, subtraction, multiplication or division depending the input from user

# include <stdio.h>

int main() {

    char operator;
    double firstNumber,secondNumber;

    printf("Enter an operator (+, -, *,): ");
    scanf("%c", &operator);

    printf("Enter two operands: ");
    scanf("%lf %lf",&firstNumber, &secondNumber);

    switch(operator)
    {
        case '+':
            printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber, firstNumber + secondNumber);
            break;

        case '-':
            printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber - secondNumber);
            break;

        case '*':
            printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber, firstNumber * secondNumber);
            break;

        case '/':
            printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber / secondNumber);
            break;

        // operator doesn't match any case constant (+, -, *, /)
        default:
            printf("Error! operator is not correct");
    }
    
    return 0;
}

Output

Enter an operator (+, -, *,): *
Enter two operands: 1.5
4.5
1.5 * 4.5 = 6.8

Explanation

C Program to Add Two Complex Numbers by Passing Structure to a Function

In the structure complex, we are using float datatype for variables, real and imag since our concern is to add any two complex numbers with a possible fractional value.

In the main() function, the real part and the imaginary part of the complex numbers are taken separtely using scanf().

The structures n1 and n2 are passed as an argument of function add(). The function computes the sum and returns the structure variable temp to the main() function.

The final result is printed using printf() throught the main() function.

Tags

#struct  #return 

Comments