Structured Programming in CUnit 19 min read
C Basics: Structure, Compilation, and First Program
Unit 1 of Structured Programming in C introduces the language’s core concepts—its history, structure, compilation process, and writing/running a simple program—with visuals of code flow, memory models, and real-world applications like eSewa’s transaction validation.
TAKEAWAYS:
- Understand C’s three-phase compilation process (preprocessing → compilation → linking) and how errors appear in each phase.
- Write a valid C program with
#include,main(), andprintf()using correct syntax and indentation. - Differentiate between source code, object code, and executable and trace how a program like a Daraz order queue (written in C) transitions from
.cto.exe. - Recognize keywords, identifiers, and operators in C and their roles in program logic (e.g.,
ifin NTC’s traffic light control). - Learn memory allocation for variables (stack vs. static) and how it affects program performance in apps like WhatsApp’s message buffers.
- Apply debugging basics (compiler warnings,
gccflags) to fix errors in programs mirroring real-world scenarios like Kathmandu traffic route optimizations.
1. Why Learn C?
C is the foundation of modern programming languages (Python, Java, C++). It powers:
- System/embedded software (e.g., NTC’s traffic light controllers use C for real-time decisions).
- High-performance applications (e.g., WhatsApp’s backend servers rely on C for low-latency message routing).
- Operating systems (Linux kernel, Windows core components).
2. Structure of a C Program
Every C program follows this mandatory structure:
#include <stdio.h> // Preprocessor directive (includes library)
int main() // Main function (entry point)
{
printf("Hello, TU!"); // Statement
return 0; // Exit status
}
Key components:
- Preprocessor directives (
#include,#define): Processed before compilation. main()function: Execution starts here. Must returnint.- Statements: End with
;. Indentation improves readability (not enforced by C).
MERMAID DIAGRAM: Program Flow
3. Compilation Process: From Code to Executable
C programs undergo three phases before running. Errors occur in each phase:
| Phase | Tool | Output | Common Errors | Real-World Example |
|---|---|---|---|---|
| Preprocessing | cpp |
Modified source | Missing #include, undefined macros |
eSewa’s transaction code fails if #include <security.h> is missing. |
| Compilation | gcc -c |
Object code (.o) |
Syntax errors, type mismatches | Daraz’s order queue crashes if for loop syntax is wrong. |
| Linking | gcc |
Executable (.exe) |
Missing libraries, undefined functions | Ncell’s billing system links to libmath for interest calculations. |
TRACE: Compiling hello.c
gcc hello.c -o hello # Compiles and links in one step
./hello # Runs the executable
Output:
Hello, TU!
4. Memory and Variables
C uses two primary memory regions:
- Stack: Stores local variables (e.g., loop counters in Pathao’s ride-matching algorithm).
- Static/Data: Stores global variables (e.g., NEPSE’s stock prices).
VARIABLE DECLARATION RULES:
- Must declare type (
int,float,char). - Cannot start with digits or use C keywords (
if,while). - Example:
int age = 25; // Valid float salary = 50000.50; // Valid int 5years = 5; // Invalid (starts with digit)
MEMORY ALLOCATION VISUAL:
graph TD
A["Stack\n(automatic, short-lived)"] --> B["Local variables\n(e.g., loop counters)"]
C["Static/Data\n(global, persistent)"] --> D["Global variables\n(e.g., NEPSE’s stock prices)"]
E["Heap\n(dynamic, malloc/free)"] --> F["User-allocated memory\n(e.g., WhatsApp’s message buffers)"]5. Input/Output with printf() and scanf()
printf(): Prints formatted output.
scanf(): Reads user input (careful: buffer overflow risk!).
EXAMPLE: Bank Loan Calculator (Nepal’s NMB Bank)
#include <stdio.h>
int main() {
float principal, rate, time;
printf("Enter principal, rate (%%), time (years): ");
scanf("%f %f %f", &principal, &rate, &time);
float interest = principal * rate * time / 100;
printf("Interest: %.2f", interest);
return 0;
}
TRACE:
| Step | Input | Output |
|---|---|---|
| 1 | 100000 8.5 5 |
Enter principal, rate (%%), time (years): |
| 2 | (User enters values) | Interest: 42500.00 |
WARNING: Always validate scanf() input to avoid crashes (e.g., scanf("%f", &rate) fails if user enters "abc").
6. Comments and Code Documentation
Types of comments:
- Single-line:
// This is a comment - Multi-line:
/* This is a block comment */
Best practice: Document why code exists (not just what it does).
// Calculate compound interest for NMB Bank loans
float compound = principal * pow(1 + rate/100, time);
7. Common Errors and Debugging
| Error Type | Example | Fix | Real-World Impact |
|---|---|---|---|
| Syntax Error | Missing ; in printf("Hi" |
Add ; |
Daraz’s order system crashes on checkout. |
| Logical Error | if (x = 5) instead of if (x == 5) |
Use == for comparison |
NTC’s traffic light turns green incorrectly. |
| Runtime Error | Dividing by zero | Add checks (if (denominator != 0)) |
eSewa transaction fails on invalid input. |
DEBUGGING TOOLS:
gcc -Wall(enables all warnings).gdb(GNU Debugger) for step-by-step execution.
In the Real World
eSewa’s Transaction Validation
- Idea: C’s
scanf()and input validation prevent fraud by rejecting non-numeric inputs (e.g.,"abc"for amount). - How: The system uses
sscanf()to parse user-entered payment details into structured data before processing.
- Idea: C’s
NTC’s Traffic Light Control
- Idea: C’s
if-elseloops and timers manage light sequences (e.g., green for 30s, yellow for 5s). - How: A real-time OS (written in C) executes:
if (current_light == GREEN) { timer = 30; // 30-second countdown }
- Idea: C’s
WhatsApp’s Message Routing
- Idea: C’s arrays store message queues (FIFO) for efficient routing.
- How: The backend uses
struct message { char text[500]; int sender_id; }to prioritize messages.
Exam Tip
- Focus on:
- Compilation phases: Know where errors occur (e.g.,
#includemissing → preprocessing error). main()structure: Always start with#include <stdio.h>andint main().- Memory regions: Stack vs. static (e.g., global variables persist).
- Input validation:
scanf()is unsafe; usefgets()for strings.
- Compilation phases: Know where errors occur (e.g.,
- Avoid:
- Forgetting
;after statements. - Using keywords as variable names (
int if = 5;→ invalid). - Ignoring warnings (
-Wallflag ingcc).
- Forgetting
- Practical question: Expect a trace of a simple program (e.g., calculate SI with given inputs). Always show:
- Code.
- Input values.
- Step-by-step output.
In the real world
eSewa Transaction Validation: Uses
scanf()with input validation to prevent fraud by rejecting non-numeric inputs (e.g., rejecting "abc" for transaction amount). The system employssscanf()to parse user-entered payment details into structured data before processing, ensuring only valid numeric values proceed to the payment gateway.NTC Traffic Light Control: Implements C’s
if-elseloops and timers to manage light sequences (e.g., green for 30 seconds, yellow for 5 seconds). The real-time OS (written in C) executes logic like:if (current_light == GREEN) { timer = 30; // 30-second countdown }This ensures synchronized traffic flow across intersections.
WhatsApp Message Routing: Leverages C’s memory management (stack/heap) for low-latency message buffers. Dynamic allocation (
malloc/free) handles variable message sizes, while static memory stores persistent user data (e.g., contact lists). The system prioritizes performance by minimizing garbage collection overhead.
Based on the TU BITM syllabus for Structured Programming in C (ITM102), unit 1.
Discussion
Loading…