Recap Challenge #2
Part of the Fundamentals section of Coddy's C journey — lesson 52 of 63.
Challenge
MediumWrite a C program that implements a simple calculator using functions. Your program should:
- Implement the following functions:
add(int a, int b): returns the sum of a and bsubtract(int a, int b): returns the difference between a and bmultiply(int a, int b): returns the product of a and bdivide(int a, int b): returns the quotient of a divided by b (handle division by zero)
- Implement a function
calculate(int a, int b, char operation)that takes two integers and an operation character (+, -, *, /) as arguments, calls the appropriate function, and returns the result. - In the main function, read two integers and a character separated by spaces (e.g.
10 5 +); the character will be one of the operator signs, or the characterq— if you readq, end the program. Usescanf("%d %d %c", &a, &b, &op)to read the input. - Use the
calculatefunction to perform the operation and display the result - Handle invalid operations and division by zero by printing
Invalid input
We recommend you use function prototypes to declaring all of the functions above the main, and then create the function itself below the main, so your code is more readable and clean
Try it yourself
#include <stdio.h>
// Declare your functions here
int main() {
// Your code here
return 0;
}
// Implement your functions hereAll lessons in Fundamentals
4Control Flow
If StatementIf - ElseElse-IfSwitch CaseTernary Conditional OperatorRecap ChallengeNested If - Else7Functions
Declare a FunctionReturn TypesParametersRecap Challenge #1Recursion BasicsFunction PrototypesRecap Challenge #23Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge