Lecture Notes: CSC1103 – Computer Programming, I
Topic 1 Key Computer Programming Principles
Total Time Allocation: 15 hours
Subtopics Covered: 1.1 to 1.11
1.1 Abstraction in [Link]
Learning Objectives
By the end of this lesson, students should be able to:
• Define abstraction and explain its role in problem solving and programming.
• Differentiate between system-level, procedural, and data abstraction.
• Use [Link] to model abstracted real-world processes.
• Apply abstraction to develop modular and reusable code.
What is Abstraction?
Abstraction in programming is the process of simplifying complex systems by focusing on
relevant details and hiding unnecessary implementation details. It allows programmers to
concentrate on what a component does, not how it does it.
It allows developers to:
• Think in higher-level terms rather than machine-level operations.
• Break down problems and focus on core logic.
• Reduce duplication and promote code reuse and clarity.
Real-World Example of Abstraction
When you use a smartphone, you interact with icons, not hardware or low-level code. You
don’t see how your input is processed — that complexity is hidden.
This is abstraction: essential details are visible, unnecessary details are hidden.
Other examples include;
System Abstraction Hidden Complexity
ATMs User enters PIN and amount Backend banking protocols
E-commerce Cart & Checkout Inventory, logistics
Types of Abstraction in Programming
1. System-Level Abstraction
• Focus: High-level models using flowcharts or diagrams
• Tools: [Link], UML, flowcharts, System models, Network diagrams
• Example: Visual modeling of Input–Process–Output systems
• Used for designing systems before writing code.
2. Procedural Abstraction
Procedural abstraction is the process of encapsulating a sequence of instructions into a
named procedure (or function).
• Hides the implementation details of what the procedure does and exposes only how
to use it.
• The user only needs to know how to call the function, not how it works.
• Focus: What a function does, not how
Example:
int sum(int a, int b) {
return a + b;
int main() {
int result = sum(5, 3); // We don’t need to know how sum works internally
This allows code to be modular, reusable, and easier to test or debug.
3. Control Abstraction
Control abstraction hides control flow details (like loops, conditionals, and branching)
behind high-level constructs. It's about simplifying "how" a program flows by using well-
defined control structures.
• Focus: How the program flows - but at a high level.
• Hides the complexity of control structures (loops, conditionals)
Example in C:
c
for (int i = 0; i < 10; i++) {
printf("%d\n", i);
}
This for loop is a control abstraction. You don't need to know how it manages iteration
internally — the compiler handles it.
Purpose:
• Reduces complexity of control flow logic
• Enables readable and high-level constructs (e.g., if, while, for)
• Makes programs less error-prone and easier to reason about
4. Data Abstraction
• Focuses on the essence of the data and hides its internal representation.
• In C, this is implemented through structures (struct) or abstract data types (ADTs)
like stacks, queues, and linked lists.
Example:
c
struct Student {
char name[50];
int age;
float gpa;
};
You use Student objects without knowing how memory is managed inside — that’s data
abstraction.
Tool in Use: [Link] for Visual Abstraction
[Link] allows us to visually represent systems through flowcharts, enabling abstraction of
real-world processes before coding begins.
Example Task: Online Student Registration System
Let’s model a simplified registration system focusing only on the major stages:
• Input: Student details (name, ID, course)
• Process: Validate, store, and confirm
• Output: Registration success/failure message
Here's the flowchart illustration:
Why Abstraction Matters in Programming
Benefit Explanation
Programmers focus on solving problems rather than technical
Simplifies complexity
details.
Promotes reuse Abstracted functions and modules can be reused in other projects.
Improves
When details are hidden, systems are easier to update and debug.
maintainability
Supports collaboration Teams can work on modules independently using interfaces.
Classroom Practice Task
Use Case: Design a flowchart for an Online Library Checkout System
Steps:
1. Accept student login and book search.
2. Process checkout based on borrowing rules.
3. Confirm and log checkout.
Tools: [Link]
Deliverable: Exported PDF with clearly labeled inputs, processes, and outputs.
AR/VR Idea:
• Use a 3D visualisation of flowcharts in a VR environment to simulate process
transitions.
Summary - Key Takeaways
• Abstraction is the foundation of structured and modular programming.
• Use system abstraction ([Link]) to model systems. Visual tools like [Link] make
abstraction tangible and collaborative.
• Use procedural abstraction to define reusable functions.
• Use data abstraction to create complex yet manageable data types.
• Abstraction helps you focus on the solution, not the underlying details.
1.2 Algorithm Design
Learning Objectives
By the end of this lesson, learners should be able to:
• Define what an algorithm is in computer programming.
• Describe the characteristics of a good algorithm.
• Design and represent algorithms using pseudocode and flowcharts.
• Apply algorithmic thinking to solve programming problems.
Definition: What is an Algorithm?
An algorithm is a step-by-step set of instructions designed to perform a specific task or
solve a problem. It is the foundation of any computer program.
Simple Example:
An algorithm for making tea:
Making a Cup of Tea
1. Boil water
2. Add tea leaves
3. Let it steep for 3 minutes
4. Pour into a cup
5. Add sugar/milk (optional)
6. Serve
In computing, algorithms must be:
• Precise (clearly defined steps)
• Finite (they eventually end)
• Effective (solve the problem correctly)
Characteristics of a Good Algorithm
Characteristic Description
Input Should take zero or more inputs
Output Should produce at least one output
Definiteness Every step must be clearly and unambiguously defined
Finiteness The algorithm must end after a finite number of steps
Effectiveness Each operation should be basic and easily performed
Characteristic Description
Generality Should solve a set of similar problems, not just one
Algorithm Design Approaches
Approach Description Example
Break the problem into Break “sort list” into “compare
Top-Down
smaller subtasks elements” + “swap if needed”
Build from the simplest Start by writing small functions, then
Bottom-Up
components upward combine
Divide and Split problem, solve parts,
Binary Search, Merge Sort
Conquer merge results
Choose the best option at each
Greedy Coin change, shortest path
step
Dynamic Store and reuse intermediate
Fibonacci series, Knapsack problem
Programming results
Algorithm Representation
Algorithms can be represented in:
1. Natural Language – e.g., "Input A and B, compare, print result"
2. Pseudocode – Text-based code-like structure/(program-like syntax)
3. Flowchart – Graphical logic/ representation using symbols and arrows
Example in Natural Language
Design an algorithm to find the largest of two numbers:
1. Start
2. Input A and B
3. If A > B, print “A is greater”
4. Else, print “B is greater”
5. End
Example in Pseudocode
BEGIN
INPUT A, B
IF A > B THEN
OUTPUT "A is greater"
ELSE
OUTPUT "B is greater"
ENDIF
END
Example Flowchart
Real-World Examples of Algorithms
Algorithm Use Case
Search Algorithm Find student by ID in a list
Sorting Algorithm Rank exam scores from highest to lowest
Encryption Algorithm Secure passwords in a login system
Pathfinding Algorithm Find shortest route in Google Maps
In-Class Practice Task
Task:
Design an algorithm (in pseudocode and flowchart) to determine whether a number is even
or odd.
Hints: Use modulo operator (%) to check divisibility by 2.
Key Takeaways
• Algorithms are the backbone of problem-solving in programming.
• Every good algorithm must be clear, finite, and effective.
• Mastery of algorithm design enhances both logic and code quality.
• Use pseudocode and flowcharts to test your logic before coding.
1.3 Control Flow (Flowgorithm)
Learning Objectives
By the end of this subtopic, learners should be able to:
• Define control flow and its role in program execution.
• Differentiate between sequential, conditional, and iterative control flows.
• Implement control flow structures using Flowgorithm.
• Use flowcharts to model program logic before coding.
What is Control Flow?
Control flow is the order in which instructions, statements, or function calls are executed in a
program.
It answers the question: “Which statement executes next?”
Control flow in programming is broadly categorized into:
1. Sequential Flow: Instructions are executed one after another in order.
2. Conditional Flow (Selection): Execution depends on a condition (e.g., if or switch).
3. Iterative Flow (Repetition): Instructions repeat until a condition is met
(e.g., while, for).
Control Flow in Flowgorithm
Flowgorithm is a visual programming tool that uses flowcharts to represent and simulate
algorithms. It allows you to:
• Build step-by-step logic without writing actual code.
• Test program behavior interactively.
• Generate pseudocode and actual source code (like C or Java) from your flowchart.
Control Flow Structures
1. Sequential Flow
• The default execution order: one instruction after another.
• Example: Reading a user’s name and printing a greeting.
Pseudocode Example:
pgsql
BEGIN
OUTPUT "Enter your name: "
INPUT name
OUTPUT "Hello, " + name
END
In C
#include <stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
scanf("%s", name);
printf("Hello, %s!\n", name);
printf("Welcome to Programming in C.\n");
return 0;
}
Explanation (Step-by-step flow)
Step Code Statement What it does
1 printf("Enter your name: "); Prompts user for input
2 scanf("%s", name); Takes input and stores it in name
3 printf("Hello, %s!\n", name); Greets the user
4 printf("Welcome to Programming..."); Prints another message
5 return 0; Ends the program
All of these happen in order, one after another, without branching or skipping — this is the
essence of sequential flow.
Flowchat Representation
2. Conditional/ Selection Flow
• Uses decision-making constructs such as if-else or switch.
• Allows programs to choose different paths based on conditions.
Example Problem: Determine if a number is positive or negative.
In C
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (number > 0) {
printf("Positive\n");
} else {
printf("Negative or Zero\n");
}
return 0;
}
Flowchart Illustration (If-Else):
3. Iterative Flow (Loops)
• Repeats a block of code while a condition is true.
• Common loops: for, while, do-while.
Example Problem: Print numbers 1 to 5.
Pseudocode:
pgsql
BEGIN
SET i = 1
WHILE i <= 5
OUTPUT i
i=i+1
ENDWHILE
END
In C
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
return 0;
}
Practical Flowgorithm Exercise
• Open Flowgorithm.
• Build a flowchart for a program that:
1. Asks the user to enter their age.
2. Prints "Adult" if age >= 18, else "Minor".
Key Takeaways
• Control flow determines how a program moves from one statement to another.
• Flowgorithm helps visualize and debug control flow before writing real code.
• Mastering if-else and looping constructs is critical for building logical programs.
Practice Task
Task: Using Flowgorithm, create a flowchart that calculates the sum of all even numbers
between 1 and 20.
In C
#include <stdio.h>
int main() {
int i, sum = 0;
for (i = 1; i <= 20; i++) {
if (i % 2 == 0) {
sum += i;
printf("Sum of even numbers from 1 to 20 is: %d\n", sum);
return 0;
1.4 Code Reuse
Definition
Code reuse refers to the practice of using existing code for new functions or software
development projects. Instead of writing new code from scratch, programmers integrate
reusable components, which saves time, reduces errors, and ensures consistency.
Objectives of Code Reuse
• Minimize duplication of effort
• Improve development efficiency
• Increase code reliability and maintainability
• Promote modular and clean software design
Forms of Code Reuse in C
Form Description Example
Reusable blocks that perform a int add(int a, int b) { return a + b;
Functions
specific task }
Contain function declarations and
Header Files (.h) #include "mathutils.h"
macros for reuse
Precompiled reusable code
Libraries Linking to math.h
(static/dynamic)
Reusable code snippets via
Macros #define PI 3.14
preprocessor
Code Commonly reused structures (loops, Custom input validators,
Snippets/Templates patterns) menu templates
Example in C
c
// File: mathutils.h
int add(int, int);
int subtract(int, int);
c
// File: mathutils.c
#include "mathutils.h"
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
c
// File: main.c
#include <stdio.h>
#include "mathutils.h"
int main() {
printf("5 + 3 = %d\n", add(5, 3));
printf("5 - 3 = %d\n", subtract(5, 3));
return 0;
}
This example demonstrates code reuse via header files and function definitions.
Advantages of Code Reuse
• Faster development time
• Fewer bugs (tested code)
• Easier maintenance
• Supports collaborative development
• Promotes modularization
Code Reuse Conceptual Model
Summary: Key Points on Code Reuse in C
Concept Example Description
Function reuse int sum(int a, int b) Write once, call many times
Header reuse #include "mathutils.h" Share declarations across files
Library reuse #include <math.h> Use existing tested utilities
Macro reuse #define MAX 100 Replace repeated constants
Best Practices
• Use descriptive function names
• Keep functions small and single-purpose
• Document reusable components clearly
• Separate reusable code in .h and .c files
• Use version control for shared modules
1.5 Code Documentation in Visual Studio
Code documentation is the process of writing explanatory notes within your source code to
help other developers (or your future self) understand how it works. Documentation helps
maintain, debug, and extend software efficiently.
In Visual Studio, documentation can include:
• Comments in code
• Summary tags (///) for generating XML documentation
• README files and project-level docs
Why Is Documentation Important?
• Improves code readability and maintainability
• Facilitates team collaboration
• Supports debugging and onboarding
• Enables code reuse and modularity
• Allows automated doc generation from comments
Types of Code Documentation in C (using Visual Studio)
Type Description Example
Single-line Used for short explanations or inline // This function adds two
Comments notes numbers
Used to explain more complex logic or
Multi-line Comments /* This loop iterates through... */
code blocks
Function Header
Describe input/output of a function See example below
Comments
Documentation Tags XML-style tags used to auto-generate /// <summary> Adds numbers
(///) help/documentation files </summary> (in C#)
Example 1: Using Comments in C (in Visual Studio)
c
#include <stdio.h>
/*
* This function adds two integers
* Params:
* a - first integer
* b - second integer
* Returns:
* The sum of a and b
*/
int add(int a, int b) {
return a + b; // Return the result
}
int main() {
int result = add(4, 6); // Call add function
printf("Result: %d\n", result); // Print result
return 0;
}
Visual Studio Features for Documentation
Feature Description
Code Lens Displays references and changes above functions
IntelliSense Uses comments to provide tooltips for parameters
For .NET/C# projects, tags like <summary>, <param> can be used
Summary Tags
to generate documentation
README Files Markdown files for general instructions and overview
Documentation Preview
Allow rendering doc previews in real time
Extensions
How to Document Effectively in Visual Studio
1. Use consistent style (e.g., K&R or Allman)
2. Document every function – inputs, outputs, side effects
3. Write meaningful comments – explain why, not what
4. Avoid obvious comments
5. Use project-level documentation ([Link], .chm help)
Visual Illustration: Code Documentation in Visual Studio
A screenshot-style diagram showing:
• Visual Studio interface
• Highlighted function comments
• Code Lens and IntelliSense tooltip
Activity (Visual Studio):
• Write a small C program with header, inline, and block comments.
• Explain each section of the code using comments.
1.6 Data Structures in [Link]
Data structures are ways of organizing and storing data in a computer so it can be accessed
and modified efficiently. In C, common data structures include arrays, structures, and
pointers—each offering different methods of storage and manipulation.
[Link] (now known as [Link]) is a cloud-based IDE that allows students to write,
execute, and share C programs online. It supports compilation, testing, and visualization of
data structures in real time.
Common Data Structures in C
Type Description Example Usage
-Collection of elements of the [Link] scores: int
marks[5];
Array same type
2. int numbers[5] = {1, 2, 3,
-Fixed-size data containers 4, 5};
Custom data type grouping struct Student {int id; char
Structure
multiple fields name[50];};
Stores address of another variable
Pointer int *p = &x;
(dynamic use)
String (char array) Sequence of characters char name[20] = "Alice";
Lists(via dynamic arrays or
linked lists)
advanced – introduce visually or
Stacks/Queues
in brief
Example 1: Using Arrays in [Link]
c
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
printf("Element %d = %d\n", i, numbers[i]);
}
return 0;
}
Try it in [Link]: Copy this code into a C project and run it to see the array output in the
terminal.
Example 2: Using Structures in [Link]
c
#include <stdio.h>
struct Student {
int id;
char name[50];
};
int main() {
struct Student s1 = {101, "Joy"};
printf("ID: %d\n", [Link]);
printf("Name: %s\n", [Link]);
return 0;
}
Explanation:
• struct Student is a user-defined data type.
• s1 is a structure variable holding both id and name.
Example 3: Using Pointers with Arrays
c
#include <stdio.h>
int main() {
int data[] = {5, 10, 15};
int *ptr = data;
for (int i = 0; i < 3; i++) {
printf("Value at [%d]: %d\n", i, *(ptr + i));
}
return 0;
}
Demonstrates how pointers interact with arrays to access values using memory addresses.
Visualization of an Array in Memory
Diagram visually explaining how an array is stored in memory and accessed via indices and
pointers.
Summary: Using Data Structures in [Link]
Feature Benefit
Arrays Store multiple values of same type
Structures Group multiple related variables
Feature Benefit
Pointers Access and manipulate memory locations dynamically
[Link] IDE Online coding, live output, and sharing environment
Activity ([Link]):
• Create a program to accept 5 student scores and print the average.
• Extend it to sort the array.
Pair Discussion:
What happens if you try to access an element outside the array size?
Optional AR/VR Idea:
Interactive 3D model showing how arrays work in memory — ideal for explaining indexes,
values, and traversal.
1.7 File Handling
File handling in C refers to reading from and writing to files using standard file input/output
(I/O) operations. It allows programs to permanently store data on disk instead of only in
memory.
Why File Handling Matters
• Enables persistent data storage
• Facilitates data sharing between programs
• Supports logging and auditing
• Critical for handling large datasets beyond memory capacity
File Operations in C
C uses a library called stdio.h to perform file operations. The key steps in file handling are:
Step Function Description
1 fopen() Opens a file
2 fprintf() / fscanf() Writes to / reads from file
3 fclose() Closes the file
4 fgetc() / fputc() Reads/writes characters
5 fgets() / fputs() Reads/writes strings
Example 1: Writing to a File
c
#include <stdio.h>
int main() {
FILE *fp = fopen("[Link]", "w"); // open file in write mode
if (fp != NULL) {
fprintf(fp, "Welcome to Programming I\n");
fclose(fp); // close file
} else {
printf("File could not be opened!\n");
}
return 0;
}
Explanation:
• "w" mode creates a file for writing.
• fprintf() works like printf() but writes to a file.
Example 2: Reading from a File
c
#include <stdio.h>
int main() {
char buffer[100];
FILE *fp = fopen("[Link]", "r"); // open in read mode
if (fp != NULL) {
fgets(buffer, 100, fp);
printf("Content: %s", buffer);
fclose(fp);
} else {
printf("File could not be opened!\n");
}
return 0;
}
Modes of File Access in C
Mode Description
r Read (fails if file doesn't exist)
w Write (creates new file or overwrites)
a Append (adds to end of file)
r+ Read and write
w+ Write and read (overwrite)
a+ Append and read
File Handling Flow
Classroom Activity – Practice File Handling
Objective: Reinforce basic file I/O in C
Activity:
1. Ask students to create a C program that:
o Accepts user input for their name and age.
o Writes it to a file called [Link].
o Reads the data back and displays it on the console.
Sample Output:
yaml
Enter your name: Joy
Enter your age: 20
Data saved!
Reading file...
Name: Joy, Age: 20
File handling flowchart illustration…
It illustrates the typical file handling sequence:
Program → fopen() → fprintf() / fscanf() → fclose() → File
1.8 Error Handling
Error handling in programming refers to the process of anticipating, detecting, and
resolving errors or unexpected conditions that occur during program execution. In C, error
handling primarily relies on conditional checks, return values, and standard error
functions from the errno.h and stdio.h libraries.
Why Error Handling Is Important
• Prevents program crashes
• Helps isolate and fix bugs
• Ensures programs behave predictably under unexpected conditions
• Improves user experience and system stability
Types of Errors in C
Error Type Description Example
Missing semicolon, invalid
Syntax Error Violates grammar rules of the C language
syntax
Runtime Occurs while program is running (e.g., file Division by zero, invalid
Error not found) memory
Logical Error Program runs but produces wrong output Using + instead of *
Example 1: Handling File Opening Error
c
#include <stdio.h>
int main() {
FILE *fp = fopen("[Link]", "r");
if (fp == NULL) {
printf("Error: Unable to open file!\n");
return 1;
}
fclose(fp);
return 0;
}
Explanation:
• Checks if file opening fails
• Prevents crashing and informs the user
Example 2: Handling Division by Zero
c
#include <stdio.h>
int main() {
int num = 5, denom = 0;
if (denom == 0) {
printf("Error: Division by zero!\n");
} else {
printf("Result = %d\n", num / denom);
}
return 0;
}
This avoids undefined behavior caused by dividing by zero.
C Error Handling Tools
Tool / Function Purpose
ferror(FILE *stream) Checks for stream-related errors
perror("msg") Prints error description to stderr
errno (from errno.h) Stores the last error number
strerror(errno) Returns a human-readable error message
Example 3: Using errno and perror
c
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
FILE *fp = fopen("[Link]", "r");
if (fp == NULL) {
perror("Error opening file");
printf("Error code: %d\n", errno);
printf("Message: %s\n", strerror(errno));
}
return 0;
}
This prints system-level error information and helps in debugging.
Best Practices for Error Handling
• Always check return values of functions
• Display clear and helpful error messages
• Use standard error mechanisms (errno, perror)
• Don’t crash—fail gracefully
• Log errors where possible for audit and debugging
Typical error handling logic in a C program
It visually illustrates:
1. Start
2. Attempt an operation
3. Check if an error occurred
4. If yes → handle error
5. If no → continue execution
6. End
Classroom Activity – Detect and Handle Errors
Task:
1. Write a program that:
o Prompts the user for a filename to open.
o If the file exists, prints "File opened successfully!"
o If the file doesn’t exist, prints an error message using perror() and errno.
Expected Output:
yaml
Enter file name: [Link]
Error opening file: No such file or directory
1.9 Manipulating Strings in RegExr
RegExr is an online tool that allows you to create, test, and debug regular expressions
(regex). Regular expressions are patterns used to match character combinations in strings:a
powerful tool for text processing and string manipulation.
Why Use Regex?
• Extract specific patterns (e.g., phone numbers, emails)
• Validate input formats (e.g., password strength, email format)
• Replace or modify parts of a string
• Search through large blocks of text efficiently
Common Regex Syntax
Pattern Meaning Example Match
. Any character except newline a.c → "abc"
* 0 or more of the previous character go*gle → "gogle", "google"
+ 1 or more go+gle → "google", not "ggle"
? 0 or 1 occurrences colou?r → "color", "colour"
\d Any digit \d+ → "123"
\w Any word character (letter, digit) \w+ → "hello123"
^ Start of string ^abc → matches "abc..."
$ End of string abc$ → matches "...abc"
Pattern Meaning Example Match
[] Character class [aeiou] → any vowel
() Group (abc)+ → "abcabc"
Using RegExr ([Link]
RegExr provides a real-time sandbox to test patterns against sample text. Features include:
• Highlighting of matches
• Explanation of pattern components
• Match history and debugging help
• Library of common patterns
Example 1: Validating an Email Address
regex
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,}$
Explanation:
• ^ ensures the string starts with valid characters
• +@ matches the @ sign
• \. matches the dot before the domain extension
• $ ensures it ends properly
Matches: [Link]@[Link]
Example 2: Matching a Phone Number
regex
^\+256\d{9}$
Matches: +256701234567
Explanation:
• Must start with +256
• Followed by exactly 9 digits
Example 3: Extracting All Words
regex
\w+
This will return all word-like tokens in a sentence.
Application in Programming
In C, regex is used via external libraries like POSIX regex (<regex.h>), but for learning
purposes, RegExr helps:
• Build the pattern
• Understand its logic
• Test on sample strings before embedding in code
Diagram – Regex Workflow Using RegExr
Classroom Activity – Exploring Regex with RegExr
Objective: Learn and practice regular expressions interactively.
Task:
1. Visit [Link]
2. Try matching the following using different patterns:
o All phone numbers in a block of text
o All words starting with capital letters
o All dates in format dd/mm/yyyy
3. Share and explain your regex patterns with a partner.
1.10 Testing and Debugging
• Testing is the process of executing a program to identify bugs or verify that it
performs as expected.
• Debugging is the process of locating, analyzing, and fixing the bugs found during
testing.
Together, testing and debugging ensure that your program is reliable, efficient, and behaves
as intended.
Goals of Testing and Debugging
• Ensure correctness of the program
• Identify and eliminate errors or bugs
• Improve code quality and maintainability
• Validate that the program meets user requirements
Types of Testing in C Programming
Type Description
Unit Testing Tests individual components or functions
Type Description
Integration Testing Tests interactions between modules
System Testing Tests the complete system as a whole
Regression Testing Tests to ensure new changes don’t break existing code
Boundary Testing Tests with input values at or near edge limits
Debugging Techniques
Technique Description
Print Statements (printf) Print variable values or messages to trace execution
Using a Debugger (gdb) Inspect program state, set breakpoints, step through code
Code Reviews Having peers examine your code
Rubber Duck Debugging Explaining your code to someone/something else
Static Code Analysis Tools Tools to automatically detect code issues (e.g., splint)
Example: Manual Test + Debug
c
Copy
#include <stdio.h>
int divide(int a, int b) {
return a / b;
}
int main() {
int result = divide(10, 0); // Runtime error: divide by zero
printf("Result: %d\n", result);
return 0;
}
Bug: Division by zero
Fix:
c
Copy
int divide(int a, int b) {
if (b == 0) {
printf("Error: Division by zero\n");
return 0; // or appropriate error value
}
return a / b;
}
Testing Tips in C
• Use assertions (#include <assert.h>) to verify assumptions
• Always check return values from functions (e.g., file I/O, malloc)
• Handle edge cases: 0, negative numbers, NULL pointers
• Modularize code for easier testing
Tools for Testing and Debugging in C
Tool Purpose
gdb GNU debugger to inspect and step through code
valgrind Memory error detection
splint Static code analyzer for C
IDE Debuggers Integrated into VS Code, Code::Blocks, etc.
Testing Flowchart Illustration
Classroom Activity – Debug a Faulty Program
Objective: Practice identifying and fixing logical and runtime errors.
Task:
• You are given a buggy C program that performs arithmetic operations.
• Test the program with various inputs.
• Find and fix any issues related to:
o Incorrect calculations
o Division by zero
o Unused variables
o Incorrect return values
Sample Error:
c
Copy
int a = 10;
int b = 0;
printf("Answer: %d\n", a / b); // crash!
Fix:
c
Copy
if (b != 0) {
printf("Answer: %d\n", a / b);
} else {
printf("Cannot divide by zero.\n");
}
1.11Programming Best Practices
Programming best practices are a set of informal rules that help developers write cleaner,
more maintainable, and error-free code. These practices enhance readability, ease debugging,
improve team collaboration, and reduce long-term development costs.
Key Categories of Best Practices
1. Code Readability
• Use meaningful variable and function names (e.g., calculateTotal(), userAge)
• Use proper indentation and spacing
• Write short and focused functions
c
// BAD
int x(int a,int b){return a+b;}
// GOOD
int addNumbers(int num1, int num2) {
return num1 + num2;
}
2. Consistent Commenting
• Use comments to explain why, not what the code does
• Avoid redundant comments
• Use block comments for functions and inline comments for tricky lines
c
// Calculate total price after discount
float applyDiscount(float price, float discount) {
return price * (1 - discount);
}
3. Modularization
• Break large programs into reusable modules or functions
• Makes code easier to test and debug
c
void getInput();
void calculateResult();
void displayOutput();
4. Code Reusability
• Avoid copying and pasting code
• Reuse functions where applicable
• Create generic functions with parameters
5. Error Handling
• Check the return values of functions like malloc(), fopen(), scanf()
• Use conditional statements to catch and manage errors gracefully
c
FILE *file = fopen("[Link]", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
6. Memory Management
• Free dynamically allocated memory using free()
• Avoid memory leaks by tracking allocation/deallocation
• Don't access freed memory
c
int *arr = malloc(10 * sizeof(int));
if (arr != NULL) {
// use array
free(arr);
}
7. Consistent Code Formatting
• Use a uniform style guide (e.g., K&R, GNU style)
• Use tools like clang-format or IDE auto-formatting
8. Version Control
• Use Git to track changes
• Commit frequently with meaningful messages
• Work on branches and use pull requests for reviews
9. Documentation
• Maintain a README file
• Document APIs, function interfaces, and usage
• Use tools like Doxygen for automatic documentation
10. Testing
• Regularly test modules individually (unit tests)
• Conduct integration tests as new features are added
• Test edge cases and invalid input
Tools to Support Best Practices
Tool Use Case
gcc -Wall Warn about common mistakes
valgrind Detect memory leaks
lint / splint Static code analysis
Git Version control and backups
IDEs (VS Code, Code::Blocks) Style enforcement, auto-complete
Visual Summary (Programming Best Practices Tree)
Student Activity:
• Refactor a messy C code snippet to follow best practices.
• Write a short function with proper documentation and formatting.
Lab Exercises
1. [Link] Activity – Abstraction
o Create a system abstraction diagram for a library management system.
2. Flowgorithm – Control Flow
o Design and simulate a flowchart for a basic calculator.
3. Code Reuse in C
o Refactor a program to reuse repeated logic via functions.
4. Documentation in Visual Studio
o Document a simple C program using comments and XML tags.
5. File I/O Practice
o Create a file, write data, then read and display it.
6. Error Handling
o Write a program to validate numeric input and handle errors.
7. String Manipulation (RegExr)
o Use regular expressions to validate email or phone formats.
Case Study
• Case Study: "Water Utility Billing System"
o Problem: Input customer details and compute monthly bills based on usage.
o Objectives: Apply abstraction, control flow, error handling, and
documentation.
Reference Materials
• Kernighan, B.W. & Ritchie, D.M. (1988). The C Programming Language.
• Flowgorithm: [Link]
• RegExr tool: [Link]
• [Link] C Environment: [Link]
AR/VR Integration
• AR Module: Interactive 3D model showing abstraction layers: system →
application → function → data types.
How It Works
1. Launch the AR Experience
o Learners scan a QR code or open an AR app on a mobile device or tablet.
o A 3D layered structure appears in their environment (e.g., on a desk).
2. Layered Visualization
o The model displays four key abstraction layers stacked like a building:
§ System Layer – OS, memory, CPU
§ Application Layer – Software programs (e.g., browsers, IDEs)
§ Function Layer – Algorithms, methods, procedures
§ Data Type Layer – Integers, strings, arrays, objects
3. Interactive Exploration
o Tap or click a layer to:
§ Zoom in and rotate
§ Trigger animations showing flow of control/data across layers
§ View tooltips or audio explanations
4. Dynamic Relationships
o Arrows and highlights show how each layer depends on or interacts with
the one below.
o Examples appear (e.g., "printf()" in function layer → OS handles it in system
layer).
5. Mini Exercises
o Short prompts like:
“Trace this function call to the system level”
or
“Which data type would be used in this application scenario?”
Learning Outcome
Students gain a clear, visual understanding of software abstraction from hardware to high-
level code, making it easier to grasp modularity, encapsulation, and design hierarchies in
programming.
• VR Simulation: Immersive debugging experience—walk through a malfunctioning
program, identify errors in logic, and suggest refactors.
A Virtual Reality (VR) simulation where students are transported inside a malfunctioning
program, allowing them to walk through its logic, spot errors, and propose fixes—as if
exploring a broken machine from the inside.
How It Works
1. Enter the Simulation
o Using a VR headset, students enter a virtual coding environment.
o The program’s logic is visualized as a 3D flow of code blocks, paths, and
data streams.
2. Navigate the Faulty Program
o Students walk through functions, conditional branches, loops, and variables as
if moving through a logic maze.
o Visual cues highlight:
§ Errors (e.g., logic flaws, null references)
§ Infinite loops
§ Dead code or unreachable branches
3. Inspect and Interact
o Use VR controllers to:
§ "Pause" the logic flow
§ Examine variable states at each step
§ Trace inputs and outputs
o Simulate stepping through code line-by-line (like a 3D version of debugging
tools).
4. Propose Refactors
o Drag and drop logic blocks to reorganize control flow.
o Suggest more efficient alternatives (e.g., replace nested loops, fix conditions).
o Submit refactored flow for instant feedback.
5. Feedback & Assessment
o At the end, the simulation gives:
§ A logic accuracy score
§ Suggestions for improvement
§ Reflection questions: “Why did the loop fail?” or “What’s the better
approach here?”
Learning Outcome
Students develop critical debugging and refactoring skills by exploring errors visually and
spatially, helping them understand logic breakdowns and fix them more intuitively than
through static code alone.
Topic 2: Programming Languages (5 hours)
2.1 Categories & Characteristics of Programming Languages
A programming language is a formal language comprising a set of instructions used to
produce various kinds of output by a computer. Programming languages are the primary tools
for software development.
Main Categories of Programming Languages
Programming languages are commonly categorized based on their level of
abstraction, programming paradigm, or execution method. Below are the most relevant
categories:
1. Low-Level vs High-Level Languages
Category Description Example Languages
Close to machine language, minimal
Assembly, Machine Code(Binary
Low-Level abstraction, requires knowledge of
code)
hardware
Closer to human language, easier to write
High-Level C, Java, Python, C++, C#, Ruby
and maintain
Designed for specific tasks
Very High- SQL for databases, MATLAB for
Level math, or Scratch for learning
C is a high-level language with low-level capabilities (close to memory and hardware).
2. Compiled vs Interpreted Languages
Type Description Examples
Translates entire code into machine code before
Compiled C, C++, Rust, Go
execution
Python, Ruby,
Interpreted Translates and executes code line-by-line
JavaScript
C is a compiled language. You must compile the code using a compiler (e.g., GCC) before
running.
3. Procedural vs Object-Oriented vs Functional Languages
Paradigm Description Examples
Procedural Code is organized into procedures/functions C, Pascal
Paradigm Description Examples
Object-Oriented Based on objects with properties and methods Java, C++, Python
Functional Emphasizes functions and immutability Haskell, Lisp, Scala
C is a procedural programming language.
4. Scripting Languages
• Scripting languages are often used to automate tasks.
• Typically interpreted, not compiled.
• Examples: Bash, Python, Perl, JavaScript
5. Domain-Specific Languages (DSLs)
• Designed for a specific problem domain (not general-purpose)
• Examples:
o SQL (databases)
o HTML (web content)
o Verilog (hardware description)
6. Statically Typed vs Dynamically Typed
Feature Description Example
Statically Typed Data types declared explicitly C, Java
Python,
Dynamically Typed Data types inferred at runtime
Ruby
Characteristics of a Good Programming Language
Characteristic Description
Simplicity Easy to learn and read
Efficiency Executes fast and uses minimal memory
Portability Runs across platforms without changes
Modularity Supports functions or modules
Error Handling Detects and reports errors properly
Support for Abstraction Hides low-level details
C provides efficiency, modularity, and close-to-hardware control, which makes it suitable for
systems programming.
Classroom Activity (Optional)
Task: In groups of 3–4, classify the following languages under the correct categories:
• C
• Python
• Assembly
• Java
• SQL
• HTML
• Rust
Discussion:
• Which language is best for system-level programming?
• Which one is better for data science tasks?
• Which are compiled? Which are interpreted?
2.2 Popular Programming Languages
Introduction
Over the years, many programming languages have emerged, each designed for specific use
cases. The popularity of a programming language is influenced by its ease of use, application
area, performance, and community support.
Globally Popular Languages (as of recent rankings like TIOBE & Stack Overflow)
Language Primary Use Cases Type Characteristics
Systems programming, Compiled, Fast, efficient, close to
C
embedded systems Procedural hardware
Data science, web apps,
Python Interpreted, OOP Easy syntax, rich libraries
automation
Enterprise applications, Compiled Platform-independent,
Java
mobile apps (JVM), OOP scalable
Web development Interpreted, Runs in browser, widely
JavaScript
(frontend/backend) Event-driven supported
Game development, system-
C++ Compiled, OOP High-performance, complex
level applications
Windows apps, game Developed by Microsoft,
C# Compiled, OOP
development runs on .NET
Go Simple, fast, built-in
Cloud systems, microservices Compiled
(Golang) concurrency
Systems programming, Safe memory handling,
Rust Compiled
performance-critical modern alternative to C
Easy for web backend,
PHP Web server scripting Interpreted
widely hosted
iOS/macOS application
Swift Compiled, OOP Apple ecosystem-focused
development
Key Factors Behind Popularity
1. Community Support
o Active forums, tutorials, and open-source libraries
2. Industry Demand
o Languages used by top tech companies (e.g., Python at Google, Java at banks)
3. Learning Curve
o Simpler syntax = faster learning (e.g., Python)
4. Versatility
o Language supports multiple domains (e.g., JavaScript on frontend and
backend)
Popularity Trends Over Time
• C continues to dominate in system-level programming.
• Python has surged in popularity due to its use in AI/ML and data science.
• JavaScript remains dominant for web development.
• Rust and Go are growing for system-level safety and concurrency.
Why Learn Multiple Languages?
• Different languages are optimized for different domains.
• Understanding paradigms (OOP, functional) enhances problem-solving ability.
Activity – Compare Two Languages
Pair Task: Choose two languages (e.g., C vs Python). Compare them in terms of:
• Syntax simplicity
• Execution speed
• Use cases
• Tools/IDEs supported
Tools/Resources for Exploration
Tool/Platform Description
Replit Online IDE for multiple languages
TIOBE Index Ranks popular programming languages
Stack Overflow Developer Q&A community
GitHub Source code hosting platform
2.3 How to Choose a Programming Language
Introduction
Choosing the right programming language for a project is a critical decision that can affect
development speed, performance, maintainability, and future scalability. This subtopic
explores the key factors that influence this choice.
Factors to Consider When Choosing a Programming Language
1. Project Requirements
• What is the application domain?
o Web (JavaScript, PHP)
o Mobile (Swift, Kotlin)
o Embedded (C)
o Enterprise (Java, C#)
2. Performance Needs
• Does the application require real-time processing or low latency?
o Use compiled and efficient languages like C, C++, or Rust
3. Developer Skillset
• Choose a language your team is comfortable with
o Team familiar with Python? Consider using it for rapid development
4. Platform Compatibility
• Will the app run on Windows, Linux, macOS, or mobile platforms?
o Java and Python are cross-platform
o Swift is iOS/macOS specific
5. Community and Library Support
• Does the language have strong open-source libraries?
o Python (e.g., NumPy, Pandas)
o JavaScript ([Link], React)
6. Tooling and IDE Support
• Are good IDEs/debuggers available for the language?
o C: Visual Studio, Code::Blocks
o Python: PyCharm, VS Code
7. Scalability and Maintainability
• Will the application scale and be easy to maintain?
o Object-oriented languages like Java and C# support modular and scalable
design
8. Security
• Are there known vulnerabilities or strong type safety?
o Rust ensures memory safety
o C requires manual memory management
Real-World Scenarios
Project Type Suggested Languages Reason
Web front-end JavaScript, TypeScript Browser-compatible, dynamic interfaces
Web back-end Python, PHP, [Link] Easy development, large ecosystems
Mobile (iOS/Android) Swift, Kotlin Platform-specific performance
Data Science/AI Python, R Strong libraries for ML, statistics
Operating Systems C, C++ Low-level hardware access
Enterprise applications Java, C# Robust, scalable, good for large systems
Activity: Language Selection Exercise
Scenario: You are building a mobile banking app.
• List 3 criteria you'd consider before choosing a language.
• Which languages would you shortlist? Why?
Summary
Choosing the right language depends on a balance of factors: the problem domain, developer
skills, available tools, and future goals. There is no universal “best language”—only the
best fit for a particular context.
2.4 Working with a New Programming Language
Introduction
Learning a new programming language is a valuable skill in a programmer's toolkit. With
evolving technology, developers are often required to switch or adapt to different languages
for different projects or platforms.
Steps for Learning a New Programming Language
1. Understand the Language Paradigm
• Is it:
o Procedural? (like C)
o Object-Oriented? (like Java or C++)
o Functional? (like Haskell)
o Multi-paradigm? (like Python or JavaScript)
Knowing the paradigm gives insight into how to structure and think about programs in that
language.
2. Set Up the Development Environment
• Install a compiler or interpreter
• Choose a suitable IDE or text editor
• Configure build tools, debuggers, and linters
Example:
To start with C:
• Install GCC
• Use Visual Studio Code or Code::Blocks
• Set up debugging and build tasks
3. Learn Syntax and Data Types
• Master the basic structure: variables, operators, conditionals, loops
• Learn how data types are defined and used
Activity: Write a simple “Hello, World!” program and expand to loops and conditionals.
4. Study Input/Output Mechanisms
• Console I/O
• File I/O
• Network I/O (if applicable)
Example:
c
printf("Enter a number: ");
scanf("%d", &num);
5. Practice with Real Problems
• Use platforms like:
o HackerRank
o LeetCode
o Codeforces
Start small:
• Basic calculator
• String manipulations
• Sorting arrays
6. Explore the Standard Library
• Learn built-in functions and modules
• Example in C: math.h, stdio.h, stdlib.h
7. Use Documentation Effectively
• Read the official documentation
• Use community-contributed tutorials
• Refer to language reference books
8. Join the Developer Community
• Follow GitHub projects
• Join forums (Stack Overflow, Reddit)
• Attend meetups or webinars
Common Challenges & Tips
Challenge Solution
Syntax errors Use an IDE with good linting/highlighting
Different memory models Read docs; test small snippets
No community in your language Choose well-supported languages first
Debugging difficulty Use step-by-step debugging tools
Activity – Self-Guided Learning Exercise
Task: Choose a new language (e.g., Go or Rust). Spend 1 hour setting it up and writing a
basic program.
Reflection:
• What were your difficulties?
• How is it different from C?
• What features did you like/dislike?
Summary
Working with a new programming language demands patience, consistency, and hands-on
practice. Emphasize:
• Understanding the language model
• Practicing through mini-projects
• Using the right tools and resources
Lab Exercises
1. Language Comparison Table
o Fill a table comparing compiled vs interpreted languages.
2. Hello World! in Multiple Languages
o Write “Hello World” in C, Python, and JavaScript.
3. Language Selection Task
o Match use cases (web app, OS kernel, AI bot) with best-fit language.
Case Study
• Case Study: “Choosing a Language for a School Management System”
o Context: Compare PHP, Java, and C based on scalability, performance, and
ease of use.
Reference Materials
• Sebesta, R.W. (2012). Concepts of Programming Languages.
• GeeksforGeeks - Programming Language Comparison
• Mozilla Developer Docs: [Link]
AR/VR Integration
• AR Module: Interactive toolkit comparing language characteristics (e.g., execution
speed, syntax, ecosystem).
• VR Simulation: Virtual tour of an app’s journey from source code → compiler →
machine code across three language environments.
Topic 3: Structured Programming in C
Structured programming is a method of programming that emphasizes clear, logical
structure, using blocks, functions, and control structures to create readable, maintainable
code. C is one of the foundational structured programming languages.
3.1 Basics of Structured Programming in C
Key Concepts
• Structured Programming Principles
o Sequence, Selection (if-else), Iteration (loops), and Modularization (functions)
• C Language Basics
o Syntax, data types, variables, constants, expressions
• Input/Output
o printf() and scanf() for console interactions
• Operators
o Arithmetic (+, -, *, /), Relational (<, >, ==), Logical (&&, ||, !)
• Comments
o Single-line (//) and multi-line (/* ... */)
Basic Program Structure in C
c
#include <stdio.h> // Preprocessor directive
int main() { // Main function
int num; // Variable declaration
printf("Enter a number: ");
scanf("%d", &num); // User input
printf("You entered: %d\n", num); // Output
return 0; // Exit status
}
Common Data Types in C
Data Type Size (in bytes) Example Values
int 2 or 4 10, -1, 0
float 4 3.14, -0.9
char 1 'a', 'Z'
double 8 2.71828
Basic C Program Workflow
1. Preprocessor: Handles #include and macros
2. Compiler: Translates C code to object code
3. Linker: Combines object files into an executable
4. Execution: Runs the executable in memory
Best Practices
• Always include comments for readability
• Use meaningful variable names
• Properly format code using indentation
• Return values in main() for clarity
Activity: Write and Run Your First Program
Task: Create a simple calculator that:
• Takes two integers as input
• Asks the user to choose an operation (+, -, *, /)
• Displays the result using switch-case
Diagram showing the basic program structure
3.2 Loops in C Programming
Loops allow programmers to execute a block of code multiple times without writing it
repeatedly. In C, loops are crucial for tasks like iterating through arrays, repeating operations,
and automating repetitive processes.
Key Concepts
• Iteration: Repeating a set of instructions
• Loop types in C:
o for loop – fixed number of iterations
o while loop – condition-based repetition
o do...while loop – executes at least once before checking condition
1. for Loop
Structure:
c
for (initialization; condition; increment) {
// code block
}
Example:
c
for (int i = 0; i < 5; i++) {
printf("Count: %d\n", i);
}
Output:
makefile
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
2. while Loop
Structure:
c
while (condition) {
// code block
}
Example:
c
int i = 0;
while (i < 3) {
printf("i = %d\n", i);
i++;
}
3. do...while Loop
Structure:
c
do {
// code block
} while (condition);
Example:
c
int i = 0;
do {
printf("i = %d\n", i);
i++;
} while (i < 3);
Use this loop when you want to ensure the block runs at least once.
Loop Control Statements
• break – Exit the loop prematurely
• continue – Skip current iteration
• goto – Jump to a labeled statement (not recommended for structured programming)
Comparison Table
Loop Type Condition Check Use Case
for Start of loop Known iteration count
while Start of loop Conditional iteration
do...while End of loop Run at least once regardless
Illustration
Example Exercise
Task: Write a C program to calculate the sum of the first n natural numbers using a for loop.
c
#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter a number: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
sum += i;
}
printf("Sum = %d\n", sum);
return 0;
}
Classroom Activity
Activity: Convert the above for loop example to a while loop and a do...while loop.
Learning Outcome: Understand the functional equivalence of loop structures with different
syntax.
3.3 – Functions in C Programming
Introduction
Functions are reusable blocks of code designed to perform a specific task. They help reduce
redundancy, improve modularity, and enhance readability.
Key Concepts
• Function Declaration (Prototype): Tells the compiler about the function's name,
return type, and parameters.
• Function Definition: Contains the actual body (logic) of the function.
• Function Call: Invokes the function to execute its block of code.
Syntax of a Function
c
return_type function_name(parameter_list) {
// code block
return value;
}
Example: Function to Add Two Numbers
c
#include <stdio.h>
// Function declaration
int add(int a, int b);
int main() {
int result = add(5, 3); // Function call
printf("Result = %d\n", result);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
Output:
ini
Copy
Result = 8
Types of Functions
Type Description Example
Standard Library Functions Built-in C functions printf(), scanf(), sqrt()
User-Defined Functions Created by programmers int sum(int a, int b)
Parameter Types
• Actual Parameters – Passed during the function call
• Formal Parameters – Used in the function definition
Passing Arguments
• Call by Value – Copies of actual arguments are passed (default in C)
• Call by Reference – Achieved using pointers
Example with Return Type void
c
void greet() {
printf("Hello, student!\n");
}
c
int main() {
greet();
return 0;
}
Diagram showing function call flow
Classroom Activity
Task: Write a program with two functions:
1. getInput() – to get input from user
2. calculateSquare() – to compute square of the input
3.4 Assignments in C Programming
Introduction
Assignments in C programming involve storing values in variables using the assignment
operator (=). It's one of the most fundamental operations in any programming language.
Key Concepts
• Assignment Statement:
o Assigns the value of the right-hand side (RHS) to the left-hand side (LHS)
variable.
o Example: x = 10;
• Data Type Compatibility:
o The type of value assigned must match the declared variable type.
o Example: float x = 3.14;
• Multiple Assignments:
o C allows chaining of assignments: a = b = c = 0;
Syntax
c
datatype variable_name = value;
Example:
c
int age = 20;
float salary = 4500.75;
char grade = 'A';
Compound Assignment Operators
Operator Meaning Example Equivalent To
= Assignment x = 5 -
+= Add and assign x += 3 x = x + 3
-= Subtract and assign x -= 2 x = x - 2
*= Multiply and assign x *= 4 x = x * 4
/= Divide and assign x /= 2 x = x / 2
%= Modulus and assign x %= 3 x = x % 3
Example Program
c
#include <stdio.h>
int main() {
int a = 10, b = 3;
a += b;
printf("a = %d\n", a); // Output: 13
a *= 2;
printf("a = %d\n", a); // Output: 26
return 0;
}
Common Mistakes
• Using == instead of = (e.g., x == 5; is a comparison, not assignment)
• Assigning values to undeclared variables
• Mismatched data types: int x = "hello"; ❌
Classroom Activity
Task:
Write a program that:
1. Declares and assigns values to variables using compound assignment.
2. Displays the result after each operation.
3.5 Strings in C Programming
Introduction
In C programming, a string is an array of characters ending with a null character '\0'.
Strings are used to store and manipulate text.
Unlike some other high-level languages, C does not have a built-in string type. Instead,
strings are handled as arrays of characters and require functions from the string.h library
for manipulation.
Key Concepts
• Strings are arrays of characters.
• The last character in a string must be '\0' (null terminator).
• Strings are defined using double quotes: "Hello" vs. single characters: 'H'.
Declaring and Initializing Strings
Method 1: Character array with size
c
char name[10] = "Alice";
Method 2: Without specifying size
c
char name[] = "Alice";
Method 3: Character-by-character with null terminator
c
char name[6] = {'A', 'l', 'i', 'c', 'e', '\0'};
Input and Output of Strings
c
#include <stdio.h>
int main() {
char name[20];
printf("Enter your name: ");
scanf("%s", name); // Note: stops input at first whitespace
printf("Hello, %s\n", name);
return 0;
}
To read full lines including spaces, use:
c
fgets(name, sizeof(name), stdin);
Common String Functions (string.h)
Function Description
strlen(str) Returns length of the string
strcpy(dest, src) Copies string src to dest
strcat(dest, src) Appends src to dest
strcmp(str1, str2) Compares two strings
strrev(str) Reverses the string (non-standard)
Remember to #include <string.h> to use these.
Example: String Manipulation
c
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";
strcat(str1, str2);
printf("Combined: %s\n", str1); // Output: HelloWorld
printf("Length: %lu\n", strlen(str1)); // Output: 10
return 0;
}
Common Mistakes
• Forgetting the null terminator ('\0')
• Overrunning array bounds (not allocating enough space)
• Using == to compare strings (use strcmp() instead)
Memory Allocation for Strings
When using pointers:
c
char *greet = "Hello"; // stored in read-only memory
Modifying greet[0] = 'h'; may cause a segmentation fault.
Use arrays when modifying strings:
c
char greet[] = "Hello"; // stored in modifiable memory
Classroom Activity
Task:
Write a program that:
• Accepts a string input from the user.
• Reverses it manually (using a loop).
• Displays the reversed string.
3.6 Pointers in C Programming
A pointer is a variable that stores the memory address of another variable. Pointers are
powerful features in C that provide direct memory access and are essential for dynamic
memory allocation, arrays, strings, and function arguments.
Key Concepts
• Pointer Declaration:
A pointer is declared using the * symbol.
c
int *ptr;
• Address-of Operator &:
Returns the memory address of a variable.
c
ptr = &x;
• Dereferencing Operator *:
Accesses the value stored at the address held by a pointer.
c
printf("%d", *ptr);
Simple Example
c
#include <stdio.h>
int main() {
int x = 10;
int *ptr = &x;
printf("Value of x: %d\n", x); // 10
printf("Address of x: %p\n", &x); // e.g., 0x7ffeecf30abc
printf("Value via pointer: %d\n", *ptr); // 10
return 0;
}
Pointer Terminology
Term Description
Pointer Variable holding address of another variable
Dereference Accessing value at memory address
NULL pointer Pointer initialized to NULL (safe default)
Pointer Arithmetic
Pointers support operations like:
• ptr++ → moves to next memory location (based on type)
• ptr-- → previous location
• ptr + n → advances by n units
• ptr - n → goes back by n units
c
int arr[3] = {10, 20, 30};
int *p = arr;
printf("%d", *(p + 1)); // 20
Pointers and Arrays
c
int arr[3] = {1, 2, 3};
int *p = arr;
printf("%d", *(p + 2)); // Outputs: 3
Here, p + 2 moves the pointer two elements ahead in memory.
Pointers and Functions
Pass-by-reference using pointers:
c
void update(int *n) {
*n = *n + 5;
}
int main() {
int x = 10;
update(&x);
printf("%d\n", x); // 15
}
Dynamic Memory with Pointers
Used with:
• malloc() – allocate memory
• free() – release memory
c
int *p = (int*) malloc(sizeof(int));
*p = 25;
free(p);
Include #include <stdlib.h> to use malloc() and free().
Common Mistakes
• Dereferencing uninitialized pointers
• Memory leaks (not freeing memory)
• Buffer overflows
Visual Illustration
Imagine:
c
int x = 5;
int *p = &x;
Variable Value Address (example)
x 5 0x100
p 0x100 0x104
*p 5 -
Classroom Activity
Task:
Write a program that:
• Accepts an integer input
• Uses a function with a pointer argument to double its value
• Displays the result
3.7 Dynamic Memory Management and Recursion
A. Dynamic Memory Management in C
What Is It?
Dynamic memory allocation allows programs to request memory at runtime, instead of
compile-time. This is essential when:
• You don’t know the exact memory size needed in advance
• You’re working with data structures like linked lists, trees, etc.
Key Functions in <stdlib.h>
Function Purpose Returns
malloc() Allocates memory (uninitialized) void pointer
calloc() Allocates & initializes memory void pointer
realloc() Resizes previously allocated mem void pointer
free() Frees allocated memory void
Example: Using malloc() and free()
c
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int n = 5;
arr = (int*) malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
for (int i = 0; i < n; i++) {
arr[i] = i + 1;
printf("%d ", arr[i]);
}
free(arr); // free the memory
return 0;
}
Common Pitfalls
• Forgetting to free() → memory leak
• Using memory after freeing → undefined behavior
• Not checking if malloc() returns NULL
Classroom Activity (Dynamic Memory):
Task:
Write a program that:
• Asks the user for the number of students
• Dynamically allocates memory for storing names
• Prints the names after collecting input
• Frees the memory
B. Recursion in C
What Is Recursion?
Recursion is when a function calls itself directly or indirectly to solve a problem.
Characteristics
• Must have a base case (to stop recursion)
• Must approach the base case with each call
Example: Factorial using Recursion
c
#include <stdio.h>
int factorial(int n) {
if (n == 0) return 1; // base case
else return n * factorial(n - 1); // recursive case
}
int main() {
printf("Factorial of 5 is %d\n", factorial(5)); // Output: 120
return 0;
}
Memory Behaviour of Recursion
• Each function call creates a new stack frame
• Too many recursive calls → stack overflow
Real-World Applications of Recursion
• File system traversal
• Tree and graph algorithms
• Parsing and evaluating expressions
Pros and Cons
Pros Cons
Elegant and concise code Slower due to stack overhead
Solves complex problems easily Difficult to debug
Classroom Activity (Recursion):
Task:
Write a program that:
• Takes a number n from the user
• Prints the nth Fibonacci number using a recursive function
3.8 Structures and Unions in C
Introduction
In C programming, Structures and Unions are user-defined data types that group different
data types under one name. They allow for better organization and management of related
variables.
Structures in C
What Is a Structure?
A Structure (struct) is a collection of variables of different data types grouped together
under a single name.
Defining a Structure
c
struct Student {
int id;
char name[50];
float score;
};
Here, Student is a structure with an int, char array, and float.
Example: Using Structures
c
#include <stdio.h>
struct Student {
int id;
char name[50];
float score;
};
int main() {
struct Student s1;
[Link] = 101;
strcpy([Link], "Alice");
[Link] = 88.5;
printf("ID: %d\nName: %s\nScore: %.2f\n", [Link], [Link], [Link]);
return 0;
}
You need #include <string.h> for strcpy().
Accessing Members
Use the dot operator (.):
c
[Link] = 100;
For pointers to structs, use the arrow operator (->):
c
struct Student *ptr = &s1;
ptr->score = 90.0;
Nesting Structures
You can have structures within structures:
c
struct Date {
int day, month, year;
};
struct Employee {
char name[30];
struct Date joiningDate;
};
Unions in C
What Is a Union?
A Union is similar to a structure, but all members share the same memory location. This
means only one member can contain a value at a time.
Declaring a Union
c
union Data {
int i;
float f;
char str[20];
};
Example: Using Unions
c
Copy
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data data;
data.i = 10;
printf("data.i = %d\n", data.i);
data.f = 220.5;
printf("data.f = %.1f\n", data.f);
strcpy([Link], "C Programming");
printf("[Link] = %s\n", [Link]);
return 0;
}
Note: Only the last assigned value is valid because all variables share memory.
Difference Between Structure and Union
Feature Structure Union
Memory Separate for each member Shared among all members
Size Sum of all members' sizes Size of the largest member
All members usable Simultaneously Only one at a time
Use Cases
• Structures: Ideal when all members are required (e.g., a student record).
• Unions: Useful when only one value is needed at a time to save memory (e.g., variant
data types in a compiler).
Classroom Activity
Task:
• Define a structure for a library book with title, author, year, and price.
• Create an array of 3 books and display their details.
Lab Exercises
1. C Program Structure
o Write a basic C program using main(), printf, scanf.
2. Loops and Functions
o Create a program with loops and user-defined functions (e.g., a factorial
calculator).
3. Arrays and Pointers
o Practice pointer arithmetic and dynamic memory allocation.
4. Structures and Unions
o Implement a student record system using struct and demonstrate memory
behavior with union.
Case Study
• Case Study: “Inventory System for a Pharmacy”
o Design using structures, file handling, loops, and error checks.
o Report includes pseudocode, C implementation, and testing scenarios.
Reference Materials
• Perry G. & Miller D. (2015). C Programming: An Absolute Beginner’s Guide.
• W3Schools C Tutorial: [Link]
• [Link] for compiling and testing C programs.
AR/VR Integration
• AR Module: Animated DevOps-style CI/CD visualization where C modules are
developed, compiled, and tested interactively.
An Augmented Reality (AR) module that lets learners see and interact with the entire
CI/CD workflow for C programming projects - from writing code to compiling, testing,
and deploying - using DevOps principles in a 3D animated, hands-on format.
How It Works
1. Launch the AR Experience
o Students use a phone, tablet, or AR headset to scan a QR code or open an app.
o A DevOps pipeline appears as a 3D animated workflow projected onto a
surface.
2. Interactive Pipeline Stages
The model shows a flowing DevOps pipeline with the following stages:
o Develop – A virtual terminal shows C code being written.
o Compile – Code is compiled in real-time; syntax errors or warnings are
highlighted.
o Test – Unit tests run automatically, and the system visually flags failed tests.
o Package – Successful builds are bundled as deployable binaries.
o Deploy – Final output is "deployed" to a simulated environment (e.g., virtual
device or embedded system).
o Feedback Loop – Animated metrics flow back to the “Develop” stage,
showing logs or test results.
3. Tap-to-Explore Interactions
o Tap a module (e.g., “Compile”) to:
§See a pop-up explaining what happens in that stage.
§View animations of gcc commands, build logs, or compiler errors.
o Tap “Test” to:
§ Reveal test case coverage.
§ Highlight test failures in red with explanations.
4. Learning Prompts & Mini Challenges
o “Which compiler flags are used for optimization?”
o “Drag this buggy C module to the test queue—what’s the output?”
o “Refactor and recompile—do all tests now pass?”
5. Scenario Mode (Optional)
o Run a real-world project simulation (e.g., C-based firmware build).
o See how a DevOps-style pipeline improves delivery speed and code quality.
Learning Outcome
Students learn how C programming integrates into modern DevOps
workflows by visually and interactively exploring each stage—making abstract tools like
compilers, test automation, and deployment pipelines concrete, engaging, and memorable.
• VR Simulation: Debug a memory leak by navigating C stack and heap in a VR
memory manager room.
A Virtual Reality (VR) simulation where students enter a visualized memory
space and navigate through the C program’s stack and heap to find and fix a memory leak -
as if walking inside a program’s memory layout.
How It Works
1. Enter the VR Memory Manager Room
o Using a VR headset, learners are placed inside a 3D room divided into two
sections:
§ Stack Room – shows function calls, local variables, return addresses.
§ Heap Room – shows dynamically allocated memory
(e.g., malloc blocks).
2. Trace the Program Flow
o The program logic is visualized step-by-step:
§ Function calls add new stack frames.
§ Heap allocations create glowing memory blocks.
§ Each block has labels (e.g., ptr1, size, source line).
3. Identify the Memory Leak
o Learners inspect heap blocks that:
§ Were allocated but never freed.
§ Have no pointer references (dangling or lost pointers).
o Use VR tools to trace:
§ Where malloc occurred
§ Whether a corresponding free() was called
§ What function allocated it
4. Simulate a Fix
oGrab the leaking pointer and:
§ Link it back to a free() statement
§ Or annotate the code visually with the correct fix
o Optionally re-run the simulation to test the fix
5. Feedback & Learning Report
o System provides:
§ Leak detected/not detected status
§ Explanation of memory lifecycle
§ Suggestions for better memory management
Learning Outcome
Students see and walk through stack and heap memory in a spatial way, helping them
deeply understand:
• Function call memory behavior
• Dynamic allocation with malloc() and free()
• Common causes of memory leaks and how to fix them
It transforms abstract C memory management concepts into a tangible, immersive
experience.
Topic 4: Capstone Project
The Capstone Project provides students with an opportunity to integrate and apply the
programming knowledge and skills they have learned throughout the course. It simulates a
real-world software development challenge and encourages creativity, problem-solving,
collaboration, and documentation.
Learning Objectives
By the end of this capstone experience, students should be able to:
1. Analyze a real-world problem and break it into sub-problems.
2. Design a structured algorithm and flowchart to solve the problem.
3. Develop a complete program using the C programming language.
4. Implement proper file handling, modular programming, and error checking.
5. Document the entire development process, including assumptions, limitations, and
testing outcomes.
6. Present the solution effectively with a working demonstration.
Project Requirements
The capstone project must:
• Be developed in the C programming language.
• Include:
o Proper use of functions and modularity.
o File handling and error management.
o Use of arrays, structures, or pointers where applicable.
o Input validation and user feedback.
• Be documented with:
o Problem statement and analysis.
o Algorithm and flowchart (optional: in Flowgorithm or [Link]).
o Full C code with inline comments.
o Sample input/output and test cases.
o Final report in PDF or DOCX format.
Capstone Project Examples (Choose One or More)
1. Student Record Management System
o Add, update, delete, and view student data.
o Store records in a file.
o Use structures and file I/O.
2. Library Book Tracking System
o Track issued and returned books.
o Use structures and functions.
3. Simple ATM Simulation
o User authentication, withdrawal, deposit, balance check.
o Use arrays and functions.
4. Billing System for a Retail Shop
o Accept items, quantities, prices.
o Generate bill summary and store in file.
5. Quiz Application
o Multiple-choice questions.
o Score calculation and result file storage.
Development Process Outline
Phase Description
Problem Analysis Define scope, input/output, constraints
Design Flowchart, pseudo code, file structure
Coding Write modular C code with functions
Testing Validate with various inputs and edge cases
Documentation Explain logic, challenges, limitations
Presentation Live demo and walkthrough
Assessment Rubric
Criterion Weight
Problem Analysis & Decomposition 10%
Algorithm Design & Modularity 20%
Functional Program 30%
Error Handling & Validation 10%
Documentation & Code Comments 10%
Criterion Weight
User Interface & Interaction 10%
Final Presentation 10%
Expected Deliverables
• Full C source code with comments
• Final report
• Presentation slides
• Flowchart or pseudocode
• Executable output or demo run (if applicable)
Classroom Activity Suggestion
Break students into small groups or let them work individually. Each student/group selects a
project, completes it in phases, and presents it in Week 12. Encourage peer reviews and demo
critiques.