Recap: Modular Calculator
Part of the Object Oriented Programming section of Coddy's C journey — lesson 5 of 61.
Challenge
EasyLet's build a modular calculator that performs basic arithmetic operations, organized across three files to practice everything you've learned about modular programming in C.
You'll create three files:
calc.h: Your header file declaring three calculator functions:add,subtract, andmultiply. Each function takes two integers and returns an integer. Protect your header with include guards using the symbolCALC_H.calc.c: Your source file containing the implementations of all three operations. Remember to include your own header to ensure declarations and definitions stay in sync.main.c: Your main file that includes the header and uses the calculator functions to perform operations based on input.
You will receive three integer inputs: a, b, and c.
In your main function, perform the following calculations and print each result on a separate line:
- The sum of
aandb - The result of subtracting
cfroma - The product of
bandc
Print the results in this format:
Sum: {result}
Difference: {result}
Product: {result}For example, with inputs 10, 5, and 3, the output would be:
Sum: 15
Difference: 7
Product: 15Try it yourself
#include <stdio.h>
#include "calc.h"
int main() {
int a, b, c;
scanf("%d", &a);
scanf("%d", &b);
scanf("%d", &c);
// TODO: Calculate the sum of a and b using the add function
// TODO: Calculate the difference of a minus c using the subtract function
// TODO: Calculate the product of b and c using the multiply function
// TODO: Print the results in the required format:
// Sum: {result}
// Difference: {result}
// Product: {result}
return 0;
}
All lessons in Object Oriented Programming
1Modular Programming Basics
Header FilesInclude GuardsSource FilesStatic FunctionsRecap: Modular Calculator4Encapsulation
Opaque Pointers ConceptDefining Opaque StructsGetters and SettersValidation in SettersRecap: Secret Box2Objects and Methods
Structs as ObjectsThe 'Self' PointerConst CorrectnessPointer vs ValueHelper MethodsRecap: Point Manager5Project: Simple Bank Account
Project SetupImplementation of Account3Object Lifecycle
Constructor PatternDestructor PatternStack InitializationDeep CopyRecap: String Wrapper6Inheritance via Composition
Struct EmbeddingThe First Member RuleAccessing Parent MembersUpcastingRecap: Shape Hierarchy