Menu
Coddy logo textTech

Recap Challenge #2

Part of the Fundamentals section of Coddy's C journey — lesson 52 of 63.

challenge icon

Challenge

Medium

Write a C program that implements a simple calculator using functions. Your program should:

  1. Implement the following functions:
    • add(int a, int b): returns the sum of a and b
    • subtract(int a, int b): returns the difference between a and b
    • multiply(int a, int b): returns the product of a and b
    • divide(int a, int b): returns the quotient of a divided by b (handle division by zero)
  2. 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.
  3. 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 character q — if you read q, end the program. Use scanf("%d %d %c", &a, &b, &op) to read the input.
  4. Use the calculate function to perform the operation and display the result
  5. 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 here

All lessons in Fundamentals