C Program for Calculator Using Function (SubRoutine)


Calculator Using Function in C

Here is the code to create a calculator using C language.

How Program Work?

First, we'll be creating a function for calculations and apply all the condition in function to perform calculations.

Next, in the main method, we'll be taking two operands from the user and an operator from user to perform an operation (calculation) i.e. addition, subtraction, multiplication, division.

Then, In main we will call a function to pass the value which user entered to function to perform the calculation.

After taking three value from the user i.e. two operands and one operator. As the function is called it will check the operator and perform the calculation and give the answer accordingly.

Calculator in C Using Function

#include <stdio.h>
//function start
double cal(double val1, double val2, char ope)
{
if(ope == '+')
{
printf("Addition of two numbers is %lf ", val1 + val2);
}
else if(ope == '-')
{
printf("Subtraction of two numbers is %lf ", val1 - val2);
}
else if(ope == '*')
{
printf("Multiplication of two numbers is %lf ", val1 * val2);
}
else if(ope == '/')
{
printf("Division of two numbers is %lf ", val1 / val2);
}
else
{
printf("Invalid operator");
}
} //function end

//main method start
void main()
{
double val1 , val2;
char ope;

printf("Enter First Number ");
scanf("%lf", &val1);

printf("Enter Second Number ");
scanf("%lf", &val2);

printf("Enter '+' for Add\n '-' for Sub\n '*' for Mul\n '/' for Div\n");
scanf(" %c", &ope);

cal(val1,val2,ope); //calling function

} //main end

Related:

Comments

Popular posts from this blog

Pseudocode to Check, Number is Odd or Even

How to Create Marksheet in C