0% found this document useful (0 votes)
12 views4 pages

C Lab 1

The document outlines a lab assignment for building a command-line calculator in C, structured into five competency levels that escalate in complexity. Each level emphasizes different programming concepts, including basic I/O, functions, defensive programming, memory management, and file I/O. The final project aims to demonstrate the foundational skills of a professional C developer through a robust and feature-rich application.

Uploaded by

Kenny Shawa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views4 pages

C Lab 1

The document outlines a lab assignment for building a command-line calculator in C, structured into five competency levels that escalate in complexity. Each level emphasizes different programming concepts, including basic I/O, functions, defensive programming, memory management, and file I/O. The final project aims to demonstrate the foundational skills of a professional C developer through a robust and feature-rich application.

Uploaded by

Kenny Shawa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MULUNGUSHI UNIVERSITY

Pursing the frontiers of knowledge

SCHOOL OF SCIENCE, ENGINEERING & TECHNOLOGY


ICT111- C Programming
Lab 1
Due-Date:29-10-2025 07hrs

C Lab: Building a Calculator

Instructions
This lab is structured as a series of escalating competencies. Each level requires you to demonstrate
mastery of a new concept while integrating and reinforcing the previous ones. The focus is on defensive
programming, clean code structure, and understanding the machine. Do not proceed to the next level
until the current one is fully, correctly, and cleanly implemented.

Overall Objective
Build a command-line calculator that evolves from a simple two-number adder to a robust, feature-rich
application.

Competency Level 1: The Foundation (Basic I/O, Operators, and Control Flow)

Core Concepts: stdio.h, variables, data types (int, float, double), arithmetic operators, if/else or switch.

The Task: Create a program that presents a menu to the user, takes two numbers and an operator (+, -,
*, /, %) as input, performs the calculation, and prints the result.

Competency Demonstration:

1. Clean User Interface: The menu is clear and re-displayed after each calculation.

2. Robust Input Handling: You must correctly use scanf (or fgets for the ambitious) to read both
numeric and character input. Handle the newline character left in the input buffer.

3. Division by Zero Check: This is non-negotiable. The program must explicitly check for division by
zero and print an error message without crashing.

4. Modular Design (Hint for the future): While a single main() function is acceptable here, the best
students will already be thinking of separating the calculation logic.
Competency Level 2: Embracing Functions and Code Organization

Core Concepts: Function declaration and definition, pass-by-value, return types.

The Task: Refactor your Level 1 solution to use separate functions for each arithmetic operation and for
the menu display.

Competency Demonstration:

1. Function Prototyping: Use clear, descriptive function names


(e.g., displayMenu(), add(), subtract(), multiply(), divide()).

2. Separation of Concerns: The main() function should handle program flow and I/O. The math
functions should only perform calculations.

3. Error Handling in Functions: The divide() function should not perform the division if the divisor
is zero. How will it communicate this error back to main()? (Consider a special return value or a
pass-by-reference error flag).

4. Code Readability: The main() function should now be much shorter and easier to read, looking
almost like pseudocode.

Competency Level 3: Defensive Programming and Advanced Input Handling

Core Concepts: Input validation, basic string handling (fgets, sscanf), error codes.

The Task: Make the calculator resilient to invalid input. A user should not be able to crash it by typing
"banana" when a number is expected.

Competency Demonstration:

1. Abandon scanf for Input: Use fgets() to read all input as a string. This prevents the myriad of
issues associated with scanf and leftover input buffers.

2. Parse Safely: Use sscanf() to parse the numeric values from the input string. Check its return
value to see if it successfully read the expected number of items.

3. Comprehensive Validation: Validate the operator and numbers after reading the entire line of
input. Provide clear, specific error messages (e.g., "'
banana' is not a valid number.").

4. Structured Error Handling: Implement a consistent way to propagate errors from low-level
functions (like input parsing) all the way back to the user.

Competency Level 4: Memory and State Management

Core Concepts: Pointers, arrays, structs, dynamic memory allocation (malloc, free).
The Task: Implement a "Memory" feature. The user should be able to store a result in one of several
memory slots (M1, M2, ...) and recall it later.

Competency Demonstration:

1. Data Structure Design: Design a struct to represent the calculator's state, including an array for
memory slots.

2. Pointer Usage: Use pointers to access and modify the memory slots.

3. Memory Lifecycle: If you use dynamic allocation (e.g., for a more complex history feature), you
must demonstrate correct use of malloc and free to avoid leaks.

4. New Commands: Add commands like 'M+' (add to memory), 'MR' (memory recall), 'MC'
(memory clear). This will require expanding your input parsing logic.

Competency Level 5: Engineering for Scale and Persistence

Core Concepts: File I/O (fopen, fprintf, fscanf, fclose), basic data persistence.

The Task: Add two features:


1. Calculation History: Maintain a list of the last N calculations in memory.
2. Save/Load: Save the calculation history and memory contents to a file on exit and reload them on
startup.

Competency Demonstration:

1. Dynamic Data Structures: The history should be stored in a linked list or a circular buffer, not a
fixed-size array that can easily overflow.

2. File Operations: Correctly open a file in read and write modes. Handle the case where the file
does not exist on first run (this is normal).

3. Data Serialization: Design a simple format for your file (e.g., plain text) to store the history and
memory state.

4. Program Lifecycle: The main() function will now have a clear structure: initialize state from file -
> run main loop -> save state to file on exit.

Final Evaluation Rubric

An A-grade project demonstrates:

 Correctness: Flawless execution for all valid inputs and graceful, informative handling of all
invalid inputs.

 Structure: Code is beautifully organized into logical functions and


files. main.c, calculator.c, calculator.h would be expected.

 Robustness: No memory leaks, no crashes, uses fgets for input, comprehensive validation.
 Clarity: Code is well-commented, variables are meaningfully named, and the control flow is easy
to follow.

 Features: Successfully implements all competencies through Level 5.

Remember, a programmer who can build this final version has not just built a calculator; they have
demonstrated the foundational skills of a professional C developer. They are ready for larger, more
complex systems programming tasks.

Good luck, and happy coding. Remember to always check your return values.

***End of Lab***

You might also like