TRM Gencp302 C Programming Fundamentals
TRM Gencp302 C Programming Fundamentals
GENCP302
NETWORKING AND
INTERNET
TECHNOLOGIES
C Programming
Fundamentals
TRAINER'S MANUAL
October, 2024
C PROGRAMMING FUNDAMENTALS
2024
AUTHOR’S NOTE PAGE (COPYRIGHT)
The competent development body of this manual is Rwanda TVET Board ©, reproduce with
permission.
● This work has been produced initially with the Rwanda TVET Board with the support
from KOIKA through TQUM Project
● This work has copyright, but permission is given to all the Administrative and
Academic Staff of the RTB and TVET Schools to make copies by photocopying or
other duplicating processes for use at their own workplaces.
● This permission does not extend to making of copies for use outside the immediate
environment for which they are made, nor making copies for hire or resale to third
parties.
● The views expressed in this version of the work do not necessarily represent the
views of RTB. The competent body does not give warranty nor accept any liability
● RTB owns the copyright to the trainee and trainer’s manuals. Training providers may
reproduce these training manuals in part or in full for training purposes only.
Acknowledgment of RTB copyright must be included on any reproductions. Any
other use of the manuals must be referred to the RTB.
iii | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
ACKNOWLEDGEMENTS
The publisher would like to thank the following for their assistance in the elaboration of this
training manual:
Rwanda TVET Board (RTB) extends its appreciation to all parties who contributed to the
development of the trainer’s and trainee’s manuals for the TVET Certificate III in Networking
and Internet Technologies, specifically for the module "GENCP302: C Programming
Fundamentals."
We extend our gratitude to KOICA Rwanda for its contribution to the development of these
training manuals and for its ongoing support of the TVET system in Rwanda
We extend our gratitude to the TQUM Project for its financial and technical support in the
development of these training manuals.
We would also like to acknowledge the valuable contributions of all TVET trainers and
industry practitioners in the development of this training manual.
The management of Rwanda TVET Board extends its appreciation to both its staff and the
staff of the TQUM Project for their efforts in coordinating these activities.
iv | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
This training manual was developed:
PRODUCTION TEAM
Authoring and Review
UWAMAHORO Bonaventure
KWIZERA Jean Paul
Validation
MVUYEKURE Jean Damascene
MANISHIMWE Yves
vi | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
TABLE OF CONTENT
vii | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
ACRONYMS
viii | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
INTRODUCTION
This trainer's manual includes all the methodologies required to effectively deliver the
module titled "C Programming Fundamentals." Trainees enrolled in this module will engage
in practical activities designed to develop and enhance their competencies.
The development of this training manual followed the Competency-Based Training and
Assessment (CBT/A) approach, offering ample practical opportunities that mirror real-life
situations.
The trainer's manual is organized into Learning Outcomes, which is broken down into
indicative content that includes both theoretical and practical activities. It provides detailed
information on the key competencies required for each learning outcome, along with the
objectives to be achieved.
As a trainer, you will begin by asking questions related to the activities to encourage critical
thinking and guide trainees toward real-world applications in the labor market. The manual
also outlines essential information such as learning hours, didactic materials, and suggested
methodologies.
This manual outlines the procedures and methodologies for guiding trainees through
various activities as detailed in their respective trainee manuals. The activities included in
this training manual are designed to offer students opportunities for both individual and
group work. Upon completing all activities, you will assist trainees in conducting a formative
assessment known as the end learning outcome assessment. Ensure that students review
the key reading and the points to remember section.
By the end of the learning outcome, the trainees will be able to:
1. Describe correctly different types of programming languages as used in computer
programming
2. Install properly C programming IDE according to the computer specifications.
3. Describe correctly different flowchart symbols according to their functions.
4. Design properly the flowchart according to the problem to be solved.
5. Develop properly the algorithms according to the problem to be solved.
Resources
Advance Preparation:
Duration: 5 hrs
• While delivering this activity, small groups may be used to identify different types of
computer programming.
Key steps:
Step 1: Introduce the activity and ask trainees to do the following questions:
i. What is a computer programming language?
ii. What is a computer programming IDE?
iii. Enumerate 2 role of programming IDE in telecommunications
iv. Give 2 types of programming languages.
Step 2: Monitor the discussion and asks trainees to write the findings on paper.
Step 3: Ask trainees to present their findings to the whole class.
Step 4: Provide an expert view and relate it to what they presented.
Step 5:Address any questions or concerns.
Step 6: Ask them to read the Key readings 1.1.1 in their manuals.
Points to Remember
Key steps:
Step 1: Introduce the topic and ask learners to read the task described below:
John has a computer which doesn’t have C Programming IDE and he needs to write a
program which will display” TVET SCHOOL”. You are asked to install C Programming
IDE in that computer.
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Demonstrate how to install C Programming IDE while demonstrating, explain all
steps to install C Programming IDE.
Step 4: Ask trainees to reinstall C Programming IDE and monitor the activity.
Step 5: Verify whether the program has been installed
Step 6: Ask trainees to read key reading 1.1.2.
Step 7: Ask trainees to perform the task provided in application of learning 1.1
● Visit the official website of the IDE (e.g., Visual Studio, Code::Blocks, Eclipse) and
download the appropriate installer or Locate the setup of C programming IDE .
● Install a C compiler (e.g., GCC for Linux/Mac, MinGW for Windows) if the IDE
doesn’t include one.
● Follow the installation instructions provided by the installer, adjusting settings as
needed.
● Set up the IDE to use the correct compiler and debugger.
● Configure paths for libraries and include files if necessary.
● Create a simple C program to ensure everything is working correctly.
● Compile and run the program to get the output.
Madam Rose needs to write a C program to display her name, but her computer lacks a C
programming IDE. you are requested install a C programming IDE on her computer.
Checklist
Duration: 5hrs
developing
Notes to theflowchart.
trainer:
● While delivering this activity, small groups may be used for description of the
flowchart symbols and steps for developing flowchart.
● Avail different photo to demonstrate how different flowchart symbols are looking
like.
Key steps:
Step 1: Introduce the activity and ask trainees to do the following question:
i. What is a flowchart?
ii. What are the importance of a flowchart in visualizing processes.
iii. What are symbols used to design a flowchart.
Step 2: Monitor the discussion and asks trainees to write the findings on paper
Step 3: Ask trainees to present their findings to the whole class.
Step 4: Provide an expert view and relate it to what they presented.
Step 5: Address any questions or concerns.
Step 6: Ask them to read the Key readings 1.2.1 in their manuals.
Points to Remember
● While delivering this activity, individual task and/or small group may be used.
● The trainer may demonstrate how design flowchart
● Trainer may use trainer guided to demonstrate the steps followed for designing
flowchart
Key steps:
Step 1:Introduce the topic and ask learners to read the task described below:
Using a flowchart Describe the steps involved in going to the cinema to watch a movie,
including actions like choosing a film, buying tickets, and making decisions, such as verifying
ShowTime availability.
Step 2:Demonstrate how to design flowchart with suitable example.
Step 3:Asks learners to be active in their groups and monitor the procedures.
Step 4:Ask trainees to present their findings to the whole class.
Step 5:Provide an expert view and relate it to what they presented.
Step 6:Ask trainees to read key reading 1.2.2.
Step 7:Ask trainees to perform the task provided in application of learning 1.2
Points to Remember
Design a flowchart
10 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Application of learning 1.2.
In southern province different sectors want to construct the playground for each school.
They need calculate the area of each ground using its length and width. Draw a flowchart
that will accept the length, width to calculate and print the area of the playground. (area =
length * width).
Checklist
11 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Indicative content 1.3: Development of an Algorithm
Duration: 10 hrs
● While delivering this activity, the trainer may use small groups.
● Avail examples of written algorithms to describe types of algorithms.
Key steps:
Step 1: Introduce the activity and request learners to answer to the following questions:
i. What is an algorithm?
ii. What is pseudo code, and how is it used in the algorithm design process?
iii. Enumerates the different types of algorithms.
Points to Remember
Structure of an Algorithm:
12 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
● Variable Declaration: Defines variables used in the algorithm.
● Beginning: Marks the start of the algorithm.
● Instructions: Contains the sequence of steps to be executed.
● End: Marks the completion of the algorithm.
• Types of Algorithms: Sequence, Branching (Selection), Loop (Repetition):
• Pseudo Code:
● The trainer may use individual based; you are supposed to demonstrate how to
develop an algorithm.
● Avail practical examples of developing an algorithm
Key steps:
Step 1: Introduce the topic and ask learners to read the task described below:
You are tasked to develop an algorithm and pseudocode to sort books on a library
bookshelf by their titles alphabetically. The library currently has a disorganized shelf
where books are placed randomly, and the librarian wants them arranged in
alphabetical order for easier access and browsing by library patrons.
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Demonstrate steps used todevelop an algorithmand explain each step
Step 4: Asktrainees to develop an algorithm and monitor the activity.
Step 5: Test a developed algorithm.
Step 6: Ask trainees to read key reading [Link] to perform application of learning 1.3
13 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Points to Remember
● Develop an algorithm
✓ Obtain detailed information on the problem.
✓ Analyse the problem.
✓ Think of a problem-solving approach.
✓ Review the problem-solving approach and try to think of a better Alternative.
✓ Develop a basic structure of the Algorithm.
✓ Optimize, Improve and refine.
● Write the pseudo code
✓ Always capitalise the initial word (often one of the main six constructs).
✓ Make only one statement per line.
✓ Indent to show hierarchy, improve readability, and show nested constructs.
✓ Always end multi-line sections using any of the END keywords (ENDIF, ENDWHILE,
etc.).
✓ Keep your statements programming language independent?
✓ Use the naming domain of the problem, not that of the implementation. For
instance: “Append the last name to the first name” instead of “name = first+ last.”
✓ Keep it simple, concise and readable.
The GB company is located in Kigali, they pay their employees using paper. Due to this issue
the employees did get easily their payroll statement. As a programmer Write an algorithm
and pseudocode to calculate and display the total monthly expenses based on various
categories like rent, groceries, utilities, and entertainment. The user should input expenses
for each category.
14 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Checklist
Algorithm:
Pseudocode:
Start
15 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Learning outcome 1 end assessment
Written assessment
1. What is a symbol in a flowchart represents the start and end of the process?
Answer: The Oval symbol.
2. What is a programming language?
Answer: A programming language is a formal language comprising a set of
instructions used to produce various outputs and implement algorithms.
3. Explain the purpose of a flowchart in software development.
Answer: A flowchart is used to visually represent the logic and sequence of an
algorithm or process, making it easier to understand and communicate the steps
involved in solving a problem or performing a task.
4. Describe the steps you would follow to install a C programming IDE like Code::Blocks
on your computer.
Answer: Steps include downloading the installer, running it, following the installation
wizard, selecting the installation directory and components, installing the software,
launching the IDE, configuring the compiler if necessary, and creating a new project
to verify the installation.
5. Compare and contrast the use of procedural programming and object-oriented
programming paradigms in software development.
Answer: Procedural programming focuses on a sequence of instructions and is ideal
for tasks with a clear procedure, while object-oriented programming organizes code
into objects that encapsulate data and behavior, making it suitable for large-scale
applications requiring modularity and reuse.
6. Evaluate the pros and cons of using an interpreted language like Python for
developing a web application.
Answer: Pros include easier debugging, platform independence, and rapid
prototyping. Cons include slower execution compared to compiled languages and
potential runtime errors that may not be detected until execution.
7. Name two programming languages commonly used for embedded systems
development.
Answer: C and C++.
8. What is the primary function of pseudo code in the development process?
Answer: Pseudo code is used to describe the logic and flow of a program in an
informal way, bridging the gap between an algorithm and its implementation in a
programming language.
16 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
9. Given a scenario where you need to automate a repetitive task in a
telecommunications system, which programming language would be most
appropriate and why?
Answer: A language like Python could be appropriate due to its simplicity, extensive
libraries, and support for automation and scripting.
10. Analyze the use of flowcharts versus pseudo code in a team setting for a large-scale
project. Which would you prefer and why?
Answer: Flowcharts might be preferred for their visual clarity and ease of
understanding for all team members, while pseudo code may be more detailed and
closer to the final implementation, aiding in smoother transitions to coding.
11. Copy and complete the following table
………………………………… …………………………………..
…………………….. …………………………………..
17 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Answer:
Name of the symbol Diagram Description
18 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Example languages include Java, C++, and Python. Primary use cases are large-scale
software systems, GUI applications, and simulations.
Answer: Compiled and interpreted languages differ in how they execute code.
Compiled Languages:
• Distribution: Only the compiled machine code needs to be distributed, not the
source code.
Advantages:
19 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Disadvantages:
Interpreted Languages:
• Error Detection: Errors are detected at runtime, potentially making debugging more
challenging.
Advantages:
• More flexibility and ease of development, suitable for scripting and rapid
prototyping.
Disadvantages:
• Runtime errors can occur, which might not be caught until the code is executed.
20 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
15. Which of the following steps would be the best starting point for creating a new
software application?
a) Writing the final code
b) Designing a flowchart or pseudo code
c) Debugging the code
d) Compiling the program
Answer: b) Designing a flowchart or pseudo code
16. In what scenario would functional programming be preferred over logic
programming?
a) Concurrent processing tasks
b) Artificial intelligence applications
c) Designing embedded systems
d) Web development
Answer: a) Concurrent processing tasks
17. Which IDE would you choose for C/C++ development if you needed a lightweight,
customizable environment?
a) Eclipse
b) Visual Studio
c) Code::Blocks
d) CLion
Answer: c) Code::Blocks
18. Pseudo code is primarily used for:
a) Debugging code
b) Writing final programs
c) Describing the steps in an algorithm
d) Designing hardware
Answer: c) Describing the steps in an algorithm
Practical assessment
[Link] need to write an algorithm and pseudocode for creating a grocery shopping list. The
program should allow the user to input items they need to buy, then display the complete
list of items.
• Algorithm:
1. Declare an empty list to store items.
2. Start the process.
3. Prompt the user to enter an item.
4. Read the item and add it to the list.
5. Ask if the user wants to add another item.
6. If yes, repeat steps 3-5.
7. If no, display the complete list of items.
8. End the process.
• Pseudocode:
Declare an empty list to store items.
21 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Start the process.
Prompt the user to enter an item.
Read the item and add it to the list.
Ask if the user wants to add another item.
If yes, repeat steps 3-5.
If no, display the complete list of items.
End the process.
Checklist
2. Develop an algorithm and pseudocode for a library management system to add and
display books. The user can enter the book's title and author, and the system should store
and display the list of books.
• Algorithm:
1. Declare a list to store books.
2. Start the process.
3. Prompt the user to enter the title and author of a book.
4. Read the title and author, and store them in a list as a book.
5. Ask if the user wants to add another book.
6. If yes, repeat steps 3-5.
7. If no, display the list of books.
8. End the process.
• Pseudocode:
Declare Books as List
Start
Do
Write("Enter book title:")
Read(Title)
Write("Enter book author:")
Read(Author)
Add (Title, Author) to Books
22 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Write("Do you want to add another book? (yes/no)")
Read(Response)
While Response = "yes"
Write("List of books in the library:")
For Each Book in Books
Write("Title: ", [Link], " Author: ", [Link])
End
[Link] an algorithm and pseudocode for a simple calculator that performs addition,
subtraction, multiplication, and division based on user inputs.
• Algorithm:
• Pseudocode:
Declare Num1, Num2, Result as Float
Declare Operation as String
Start
23 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Write("Enter the first number:")
Read(Num1)
Write("Enter the second number:")
Read(Num2)
Write("Choose an operation (+, -, *, /):")
Read(Operation)
If Operation = "+"
Result = Num1 + Num2
Else If Operation = "-"
Result = Num1 - Num2
Else If Operation = "*"
Result = Num1 * Num2
Else If Operation = "/"
If Num2 != 0
Result = Num1 / Num2
Else
Write("Error: Division by zero")
End
Write("The result is: ", Result)
End
END
24 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Further information to the trainer
A. Books
Graham, D. L. (2019). C Programming Language: A Step by Step Beginner's Guide to Learn C
Programming. Amazon.
B. Websites
[Link]
ppt?utm_medium=cpc&utm_source=google_pmax&utm_campaign=3Q_Google_Performan
ce-
Max_RoW&utm_term=&utm_device=c&gclid=CjwKCAjw36GjBhAkEiwAKwIWyYBOAwSwzU
Dmki-xCos35zYEx-s7uQqw4Q2rHSpf2FG2VySd7fYxMRoCmJAQAvD_BwE#
[Link]
[Link]
[Link]
25 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Learning Outcome 2: Write C Programming Codes
26 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Indicative contents
27 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Duration: 50 hrs
By the end of the learning outcome, the trainees will be able to:
Resources
Advance Preparation:
28 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Indicative content 2.1: Description of C Building Blocks
Duration: 5hrs
Key steps:
Step 1: Introduce the activity and ask trainees to do the following questions:
i. What is a token in the context of the C programming language?
ii. How are tokens used to represent fundamental building blocks in C code?
iii. Name and describe the five main categories of C tokens.
iv. What are identifiers in C, and how do they differ from keywords?
v. Give examples of valid and invalid identifiers in C.
vi. Explain the role of keywords in C and provide some examples.
vii. Name the three primary types of constant tokens in C.
Step 2: Monitor the discussion and asks trainees to write the findings on paper
Step 3: Ask trainees to present their findings to the whole class.
Step 4: Provide an expert view and relate it to what they presented.
Step 5: Address any questions or concerns.
Step 6: Ask them to read the Key readings 2.1.1
Points to Remember
In C programming, tokens are fundamental units that the compiler interprets. They
encompass keywords, identifiers, constants, operators, punctuation symbols, whitespace,
and comments, serving as the basic building blocks of C syntax:
29 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
● Keywords: Reserved words with predefined meanings, like int, float, if, else, etc.
● Identifiers: User-defined names for variables, functions, etc., following specific
rules and case-sensitive.
● Constants: Fixed values like integer (123), floating-point (3.14), character ('A'),
and string literals ("Hello").
● Operators: Symbols performing operations (arithmetic, relational, logical, bitwise,
assignment, etc.) on variables.
● Punctuation Symbols: Special characters (, ,, ;, : :, (), {} {}, []) that structure C code.
● Whitespace: Spaces, tabs, newlines used for token separation, ignored by the
compiler.
● Comments: Provide non-executable information to programmers (// Single-line,
/* Multi-line */).
● The trainer may use individual based; you are supposed to demonstrate how to
write the Data types in a c program.
● Avail visual aids, such as images, text, or code examples, to illustrate the concept
of C variable declaration.
Key steps:
Step 1:Introduce the topic and ask learners to read the task described below:
John, a computer science student, is tasked with developing a program that manages
inventory for a small retail store. His program needs to handle different types of
data, from item quantities to prices, and ensure accurate calculations and storage of
information. Write all data types John needs to complete his task.
Step 2:Explain the task and provide clear work instruction (Task, Time allocated)
Step 3:Ask trainees to discuss by listing all the needed data types.
Step 4: Ask trainees to write down the findings
30 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Step 5:Ask trainees to Present the findings to the class.
Step 6: Ask trainees to read key reading 2.1.2 Trainee Manual
Points to Remember
● Choosing Appropriate Data Types: Selecting the right data type (int, float, char,
etc.) based on the nature and range of the data ensures proper storage and
manipulation.
● Variable Declaration and Initialization: Variables must be declared with a specific
data type, and initializing them at the time of declaration ensures they start with
a defined value.
● Operations and Expressions: Data types dictate how operations (arithmetic,
relational, logical, bitwise) are performed and how values are interpreted.
● Type Casting: Type casting allows conversion between data types, with implicit
casting done automatically and explicit casting requiring programmer
intervention.
● Memory Allocation: Data types determine the amount of memory allocated to
variables, affecting how arrays and structs manage contiguous memory.
Key steps:
Step 1: Introduce the topic and ask learners to answer the task described below:
i. Name the three fundamental variables in C.
ii. what is the Rules to write variable names?
iii. Explain the differences between local, global and static variables in C.
31 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
iv. What is the syntax for declaring and initialising variables in C?
v. Explain the importance of initialising variables when declaring them.
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Ask trainees to discuss on given tasks by writing the findings
Step 4: Ask trainees to present to the whole class
Step 5: Ask trainees to read key reading 2.1.3
Points to Remember
Variables in c programming
● Variable Naming Rules: Variable names must start with an alphabet, can include
numbers, but cannot contain special characters or spaces (except the underscore)
and should not be a reserved word.
● Declaration of Variables: Variables must be declared before use, specifying the
data type (e.g., int x;).
● Assigning Values: Values can be assigned to variables either during or after
declaration using the assignment operator (=).
● Types of Variables: Variables in C can be local, global, or static, each with
different scopes and lifetimes.
● Local vs. Global Variables: Local variables are accessible only within the block
they're declared in, while global variables are accessible throughout the entire
program.
Key steps:
Step 1: Introduce the topic and ask learners to answer the task described below:
32 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
i. What is a constant in C programming?
ii. Why are constants used in programming, and what benefits do they offer?
iii. Name and describe the three main types of constants in C.
iv. Explain the format and syntax of integer constants in C.
v. Describe how floating-point constants are represented in C.
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Demonstrate the use of constraint in a c program
Step 4: Aske trainees to discuss on the given topic and write down their finding.
Step 5: Ask trainees to present their finding to the whole class
Step 6: Provide more clarification of the presentation
Step 7: Ask trainees to read key reading 2.1.4 Trainee Manual
Points to Remember
Constants in C Programming
Constants are fixed values that do not change during the execution of a program, and they
are also known as literals. C programming supports several types of constants namely:
✓ Integer Constants
✓ Character Constants
✓ String Constants
Key steps:
33 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Demonstrate the use of operators in a c program
Step 4: Aske trainees to discuss on the given topic and write down their finding.
Step 5: Ask trainees to present their finding to the whole class
Step 6: Provide more clarification of the presentation
Step 7: Ask trainees to read key reading 2.1.5 Trainee Manual
Points to Remember
C programming operators
✓ Arithmetic Operators (+, -, *, /, %) for basic math operations.
✓ Relational Operators (==, !=, >, <, >=, <=) for comparing values.
✓ Logical Operators (&&, ||, !) for combining or negating conditions.
✓ Bitwise Operators (&, |, ^, ~, <<, >>) for manipulating data at the bit level.
✓ Assignment Operators (=, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=) for assigning
and updating values.
✓ Unary Operators (+, -, ++, --, !, ~) for operations on a single operand.
✓ Ternary Operator (?:) for conditional decisions.
✓ Special Operators (sizeof, &, *, ->, .) for size checking, memory access, and
structure manipulation.
Ann is a programmer with career, she is going to hire another to help him, the following is
the written exam to pass before to be [Link] and initialize the following variables
with appropriate data types and values.
1. An integer variable year with a value of 2024.
2. A float variable pi with a value of 3.14.
3. A double variable gravity with a value of 9.81.
4. A character variable grade with a value of 'A'.
5. A string variable greeting with the value "Hello, World!"
Solution:
#include <stdio.h>
int main() {
int year = 2024;
34 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
float pi = 3.14f;
double gravity = 9.81;
char grade = 'A';
char greeting[] = "Hello, World!";
printf("Year: %d\n", year);
printf("Pi: %.2f\n", pi);
printf("Gravity: %.2lf\n", gravity);
printf("Grade: %c\n", grade);
printf("Greeting: %s\n", greeting);
return 0;
}
Checklist
35 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Indicative content 2.2: Description of C Program Structure
Duration: 5 hrs
Key steps:
Step 1: Introduce the activity and ask trainees to do the following questions:
i. What is the purpose of pre-processor directives in C?
ii. How is the #include directive used to include header files in C code?
iii. What is the difference between including header files with angle brackets
(<>) and double quotes (" ")?
iv. How do you define a constant using the #define directive, and what are the
advantages of doing so?
v. What is conditional compilation, and how is it achieved using pre-processor
directives in C?
Step 2: Monitor the discussion and asks trainees to write the findings on papers.
Step 3: Ask trainees to present their findings to the whole class.
Step 4: Provide an expert view and relate it to what they presented.
Step 5: Address any questions or concerns.
36 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Points to Remember
Preprocessor commands in c
● #include: Used to include the contents of a header file into the source code,
allowing access to external code or libraries (e.g., #include <stdio.h>).
● #define: Used to create macros, which are symbolic names for values or code
fragments that are replaced by their definitions during preprocessing (e.g.,
#define PI 3.14159265).
● #ifdef, #ifndef, #else, #endif: Used for conditional compilation, allowing code to
be included or excluded based on preprocessor-defined conditions (e.g., #ifdef
DEBUG).
● #undef: Used to undefine a previously defined macro (e.g., #undef
DEBUG_MODE).
● #error: Generates a compilation error with a custom message, useful for
enforcing certain conditions during compilation (e.g., #error "MY_CONST is not
defined!").
● #pragma: Provides additional information to the compiler or controls certain
compiler-specific behavior. Its usage can vary between different compilers.
● #line: Changes the line number and filename reported by the compiler, often
used in code generation tools and for debugging.
37 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Key steps:
Step 1: Introduce the activity and ask trainees to do the following questions:
i. What is a function in C, and why is it used in programming?
ii. How do you declare a function in C?
iii. Explain the difference between types of function in C.
iv. Give an example of a types function.
v. What is the purpose of a return statement in a C function, and how is it used?
Step 2: Monitor the discussion and asks trainees to write the findings on papers.
Step 3: Ask trainees to present their findings to the whole class.
Step 4: Provide an expert view and relate it to what they presented.
Step 5: Address any questions or concerns.
Step 6: Ask them to read the Key readings 2.2.2
Points to Remember
Functions in C
Definition of a Function
A function in C is a block of code that performs a specific task, helping to organize, improve
readability, and reuse code.
Types of Functions in C
1. Library Functions: Predefined in C standard libraries (e.g., printf(), scanf()).
2. User-defined Functions: Created by the programmer to perform custom tasks.
38 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Key steps:
Step 1: Introduce the activity and request learners to respond to the following questions:
i. What is a variable in the context of C programming, and why are they
important?
ii. How do you think variables help us store and manipulate data in a C
program? Can you provide examples?
iii. Why is it important to choose meaningful names for variables? What could
go wrong if you use vague or unclear names?
iv. What are some of the basic data types in C, and how do they affect the types
of values a variable can store?
v. When you declare a variable, what information must you specify, and why is
it necessary?
vi. Differentiate declaring and defining a variable in C? What's the key
distinction?
vii. What happens if you try to use a variable before declaring it? Why is it
important to declare a variable before using it?
viii. How do you assign a value to a variable in C programming? Can you provide
an example?
ix. Why do you think it's essential to understand the scope of a variable in a
program? How can variable scope impact your code?
x. Describe the process of initialising a variable in C, and why is it considered
best practices?
Step 2: Monitor the discussion and asks trainees to write the findings on paper
Step 3: Ask trainees to present their findings to the whole class.
Step 4: Provide an expert view and relate it to what they presented.
Step 5: Address any questions or concerns.
Step 6: Trainer orient them to read the key reading 2.2.3 Trainee Manual
Points to Remember
Variables in C Programming
Variables are fundamental components in C used to store and manipulate data. They
represent named memory locations for storing values and come in various data types.
• Data Types
39 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
C supports several basic data types:
Key steps:
Step 1: Introduce the topic and ask learners to read tasks described below:
In your formed group apply the concepts of variables, data types, initialization,
and arithmetic operations in C programming by creating a simple program to
calculate the areas of a rectangle and a circle.
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Ask trainees to discuss how initialize, and the use of data type in a given task.
Step 4: Ask trainees to write their finding on paper
Step 5: Ask trainees to present their findings to the whole class
Step 6: Ask trainees to read key reading 2.2.4 Trainee Manual.
40 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Points to Remember
Applying variables in C
Key steps:
Step 1: Introduce the activity and ask trainees to do the following questions:
i. What is the fundamental difference between a statement and an
expression in C programming, and can you provide examples of each?
ii. How are statements used to control the flow of execution in a C
program? Can you give an example of a control statement and its
purpose?
iii. Explain the role of expressions in C programming. How are expressions
evaluated, and what are some common examples of expressions?
41 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Step 2: Monitor the discussion and asks trainees to write the findings on papers.
Step 3: Ask trainees to present their findings to the whole class.
Step 4: Provide an expert view and relate it to what they presented.
Step 5: Address any questions or concerns.
Step 6: Ask them to read the Key readings 2.2.5 Trainee Manual
Points to Remember
Key steps:
Step 1: Introduce the activity and request learners to respond to the following
questions:
i. What are comments in C programming, and what is their primary
purpose when writing code?
42 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
ii. Explain the different types of comments used in C programming, such as
single-line comments and multi-line comments. Can you provide
examples of each?
Step 2: Monitor the discussion and asks trainees to write the findings on paper
Step 3: Ask trainees to present their findings to the whole class.
Step 4: Provide an expert view and relate it to what they presented.
Step 5: Address any questions or concerns.
Step 6: Trainer orients them to read the key reading 2.2.6 Trainee Manual
Points to Remember
Comments in c programming
● Types of Comments: In C, comments can be single-line (using //) or multi-line
(enclosed in /* */).
● Code Explanation: Use comments to clarify complex or non-intuitive code,
making it easier to understand.
● Documentation: Comments can describe the purpose, usage, and behavior of
functions, variables, and data structures.
● Code Organization: Comments can help separate and organize different sections
of code for better readability.
● Best Practices: Comments should be clear, concise, up-to-date, used sparingly,
and focus on explaining the "why" rather than the "what" of the code.
Rwanda BGD want to manage your daily expenses. As you are a programmer, declare two
integer variables representing amounts spent on two different items. Perform addition,
subtraction, multiplication, and division on these amounts to understand your total and
average spending. Print the results to see your calculations.
Solution:
#include <stdio.h>
int main() {
// Declare two integer variables for daily expenses
int expense1 = 50; // Amount spent on groceries
int expense2 = 30; // Amount spent on transport
43 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
// Perform arithmetic operations
int total = expense1 + expense2;
int difference = expense1 - expense2;
int product = expense1 * expense2;
float quotient = (float)expense1 / expense2;
44 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Indicative content 2.3: Applications of Condition Statements
Duration: 15 hrs
Key steps:
Step 1: Introduce the activity and request learners to respond to the following questions:
i. What is a conditional statement, and why is it an essential concept in
programming?
ii. Provide an example of a real-life situation where you would use a conditional
statement to make a decision or perform different actions based on a specific
condition.
iii. Explain the 'if' statement in C programming, including how it works, its
syntax, and its purpose? Additionally, clarify the concept of 'else if'
statements and their use cases compared to multiple 'if' statements, and
describe when and how to use nested 'if' statements in your code."
iv. What is a "switch" statement, and how does it differ from "if" statements?
v. Describe the conditions or scenarios in which you would choose to use "if"
statements over "switch" statements, and vice versa.
Step 2: Monitor the discussion and asks trainees to write the findings on paper
Step 3: Ask trainees to present their findings to the whole class.
Step 4: Provide an expert view and relate it to what they presented.
Step 5: Address any questions or concerns.
Step 6: Trainer orients them to read the key reading 2.3.1 Trainee Manual
45 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Points to Remember
1. 'if' Statement in C:
• Used to execute code blocks only if a condition is true. The syntax includes if
(condition) { code }.
• else if statements allow checking multiple conditions, providing more control
than multiple standalone if statements.
• Nested if statements enable more complex decision-making by placing if
statements inside other if statements.
2. Switch Statements:
• Used for handling multiple possible values of a single variable, often
simpler and more readable than using multiple if statements.
● The trainer may use small groups to solve problem using if statement.
● Avail daily life examples where if statement is used.
Key steps:
Step 1: Introduce the topic and ask learners to read tasks described below:
You need to implement a feature in a shopping application that checks if a
customer is eligible for a discount based on the amount they spend. The rules for
the discount are as follows:
• If the total purchase amount is greater than or equal to $100, the
customer receives a 10% discount.
• If the total purchase amount is less than $100, no discount is applied.
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
46 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Step 3: Ask trainees to discuss by writing the pseudocode of a given task.
Step 4: Ask trainees to convert the written pseudocode into program code by using if
statement syntax.
Step 5: Ask trainees to present their finding to the class.
Step 6: Ask trainees to ask clarification where necessary.
Step 7: Step 6: Ask trainees to read key reading 2.3. Trainee Manual
Points to Remember
If statement in C programming
Syntax of if Statement
if (condition) {
// code to execute if condition is true
}
Components
• Condition
• Block of Code
● The trainer may use small groups to solve problem using if statement.
● Avail daily life examples where else if statement is used.
Key steps:
Step 1: Introduce the topic and ask learners to read tasks described below:
You need to implement a feature in an educational application that assigns a
letter grade to a student based on their score. The grading criteria are as follows:
47 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
• A score of 90 or above receives an "A".
• A score of 80 to 89 receives a "B".
• A score of 70 to 79 receives a "C".
• A score of 60 to 69 receives a "D".
• A score below 60 receives an "F".
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Ask trainees to discuss by writing the pseudocode of a given task.
Step 4: Ask trainees to convert the written pseudocode into program code by using else
if statement syntax.
Step 5: Ask trainees to present their finding to the class.
Step 6: Ask trainees to ask clarification where necessary.
Step 7: Ask trainees to read key reading 2.3. Trainee Manual
Points to Remember
else if statement in c
Syntax of else if
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition1 is false and condition2 is true
} else if (condition3) {
// Code to execute if condition1 and condition2 are false and condition3 is true
} else {
// Code to execute if none of the above conditions are true
}
Components
• Initial if Statement
• else if Statements
• Optional else Statement
48 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Practical Activity 2.3.4: Solving problem using switch statement in c programming
● The trainer may use small groups to solve problem using if statement.
● Avail daily life examples where else if statement is used.
Key steps:
Step 1: Introduce the topic and ask learners to perform tasks described below:
You want to create a simple calculator application that allows users to choose an
arithmetic operation (addition, subtraction, multiplication, or division) from a
menu. The program should then perform the selected operation on two
numbers provided by the user.
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Ask trainees to discuss by writing the pseudocode of a given task.
Step 4: Ask trainees to convert the written pseudocode into program code by using
switch statement syntax.
Step 5: Ask trainees to present their finding to the class.
Step 6: Ask trainees to ask clarification where necessary.
Step 7: Ask trainees to read key reading 2.3. 4 Trainee Manual
Points to Remember
Switch Statement
Executes one code block among many options based on a variable's value, offering a
cleaner alternative to multiple if...else if statements.
• Expression Evaluation:
• Case Labels:
49 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Case labels represent possible values for the expression. If a match is found, the
associated code block is executed.
• Break Statement:
Used to exit the switch block after a case is executed; prevents "fall-through" to
subsequent cases unless intended.
• Default Case:
● The trainer may use small groups to solve problem using if statement.
● Avail daily life examples where else if statement is used.
Key steps:
Step 1: Introduce the topic and ask learners to read tasks described below:
You need to decide what to wear based on the weather conditions and the
type of event you plan to attend. The choices depend on whether it is a
formal event or a casual outing, combined with the weather being sunny,
rainy, or cold.
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Ask trainees to discuss by writing the pseudocode of a given task.
Step 4: Ask trainees to convert the written pseudocode into program code by using
nested if syntax.
Step 5: Ask trainees to present their finding to the class.
Step 6: Ask trainees to ask clarification where necessary.
Step 7: Ask trainees to read key reading 2.3.5 Trainee Manual
50 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Points to Remember
Nested conditions in C refer to using conditional statements, such as if, else if, and else,
within other conditional statements.
if (condition1) {
// Code block executed if condition1 is true
if (condition2) {
// Code block executed if condition1 and condition2 are true
} else {
// Code block executed if condition1 is true and condition2 is false
}
} else {
// Code block executed if condition1 is false
if (condition3) {
// Code block executed if condition1 is false and condition3 is true
} else {
// Code block executed if condition1 and condition3 are false
}}
ABC Company seller of movie. They need to hire a programmer to Write a program that
calculates the price of a movie ticket based on the customer's age and the time of day they
wish to watch the movie. The program should apply different pricing rules based on these
conditions.
Solution:
#include <stdio.h>
int main() {
double ticketPrice;
scanf("%d", &age);
51 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
// Prompt the user to enter the movie time
scanf("%d", &time);
} else {
return 0;
Checklist
52 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Indicative content 2.4: Applications of Loops
Duration: 10 hrs
Key steps:
Step 1: Introduce the activity and request learners to respond to the following questions:
i. What is a loop in programming, and why do we use loops?
ii. How does a "while" loop work, and what's its primary purpose?
iii. What are the key differences between a "for" loop and a "while" loop?
iv. Can you provide a practical example of when you might use a loop in a
real-life situation?
v. Why is it important to have a clear exit condition for loops to prevent
them from running infinitely?
vi. How does a loop help in avoiding repetitive and redundant code in a
program?
Step 2: Monitor the discussion and asks trainees to write the findings on paper
Step 3: Ask trainees to present their findings to the whole class.
Step 4: Provide an expert view and relate it to what they presented.
Step 5: Address any questions or concerns.
Step 6: Trainer orients them to read the key reading 2.4.1 Trainee Manual
Points to Remember
Loops in c programming
• For Loop:
53 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Used when the number of iterations is known beforehand; includes initialization,
condition, and increment/decrement in one line.
• While Loop:
Ideal for scenarios where the number of iterations is not predetermined; continues
as long as the condition is true.
• Do-While Loop:
Similar to a while loop but ensures the loop body executes at least once before the
condition is checked.
break exits the loop immediately, continue skips the current iteration, and goto
transfers control to a labeled statement.
● The trainer may use small groups to solve problem using for loop.
● Avail daily life examples where for loop is used.
Key steps:
Step 1: Introduce the topic and ask learners to perform tasks described below:
You are developing a simple voting system where users can vote for different
candidates. After collecting the votes, you need to count and display the number
of votes each candidate received.
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Ask trainees to discuss by writing the pseudocode of a given task.
Step 4: Ask trainees to convert the written pseudocode into program code by using for
loop syntax.
Step 5: Ask trainees to present their finding to the class.
Step 6: Ask trainees to ask clarification where necessary.
Step 7: Ask trainees to read key reading [Link] Manual
54 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Points to Remember
● The trainer may use small groups to solve problem using while loop.
● Avail daily life examples where else while loop is used.
Key steps:
Step 1: Introduce the topic and ask learners to perform tasks described below:
You are developing a basic ATM system that allows users to withdraw money from
their account. The system needs to repeatedly prompt the user to enter the amount
they wish to withdraw, ensure the amount does not exceed their balance, and check
if it is a valid withdrawal amount. The loop should continue until the user
successfully withdraws the amount or decides to cancel the transaction.
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Ask trainees to discuss by writing the pseudocode of a given task.
Step 4: Ask trainees to convert the written pseudocode into program code by using while
syntax.
Step 5: Ask trainees to present their finding to the class.
Step 6: Ask trainees to ask clarification where necessary.
Step 7: Ask trainees to read key reading 2.4.3 Trainee Manual
55 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Points to Remember
while (condition) {
● The trainer may use small groups to solve problem using do while.
● Avail daily life examples where do while is used.
Key steps:
Step 1: Introduce the topic and ask learners to perform tasks described below:
You are developing a user authentication system that prompts the user to enter
their password. The system should continue to prompt the user until they enter
the correct password or choose to cancel after a certain number of failed
attempts. You want to ensure that the prompt is displayed at least once,
regardless of whether the password is correct on the first try.
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Ask trainees to discuss by writing the pseudocode of a given task.
Step 4: Ask trainees to convert the written pseudocode into program code by using do
while syntax.
Step 5: Ask trainees to present their finding to the class.
Step 6: Ask trainees to ask clarification where necessary.
Step 7: Ask trainees to read key reading 2.4.4 Trainee Manual
56 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Points to Remember
do {
} while (condition);
● The trainer may use small groups to solve problem using nested loops.
● Avail daily life examples where nested loops is used.
Key steps:
Step 1: Introduce the topic and ask learners to perform tasks described below:
You are developing a program that needs to generate and display a
multiplication table for numbers from 1 to 10. This involves creating a table
where each cell in the table represents the product of the row and column
numbers.
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Ask trainees to discuss by writing the pseudocode of a given task.
Step 4: Ask trainees to convert the written pseudocode into program code by using
nested loop syntax.
Step 5: Ask trainees to present their finding to the class.
Step 6: Ask trainees to ask clarification where necessary.
Step 7: Ask trainees to read key reading 2.4.5. Trainee Manual
57 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Points to Remember
// Code to be executed
You are organizing a 3-day conference in ATL hotel in Kigali with multiple sessions each day.
Each session has multiple activities, such as presentations, workshops, and discussions. You
need to create a schedule that covers all sessions and their activities over the 3 days. To do
this, you'll need to use nested loops to iterate through each day, each session of the day,
and each activity in the [Link] a c program make these activities.
Solution:
#include <stdio.h>
int main() {
58 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
for (int j = 0; j < 3; j++) {
return 0;
Checklist
59 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Indicative content 2.5: Applications of Functions
Duration: 5 hrs
Key steps:
Step 1: Introduce the activity and request learners to respond to the following questions:
Step 2: Monitor the discussion and asks trainees to write the findings on paper
Step 6: Trainer orients them to read the key reading 2.5.1 Trainee Manual
Points to Remember
Function in c
• Library Functions:
60 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Predefined functions provided by C libraries, such as scanf(), printf(), and sqrt().
• User-Defined Functions:
• Passing Parameters:
Parameters are declared in the function definition, while arguments are the values
passed during function calls.
• Calling Methods:
Call by Value passes a copy of the argument’s value, while Call by Reference passes
the argument’s address, affecting the original argument.
Key steps:
Step 1: Introduce the activity and request learners to respond to the following questions:
You are developing a simple student grade management system for a school. The
system needs to perform several tasks:
Add Student Grades: Record grades for multiple subjects for each student.
Calculate Average Grades: Compute the average grade for each student.
Determine Grade Category: Categorize students based on their average grade (e.g.,
Excellent, Good, Average, Needs Improvement).
Step 2: Monitor the discussion and asks trainees to write the findings on paper
Step 3: Ask trainees to present their findings to the whole class.
Step 4: Provide an expert view and relate it to what they presented.
61 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Step 5: Address any questions or concerns.
Step 6: Trainer orients them to read the key reading 2.5.2 Trainee Manual
Points to Remember
LDT Company located in Karongi district, need to make a calculator. Write a C program to
create a calculator that illustrates the following tasks:
• Defining functions
• Declaring functions
• Calling functions
Solution:
#include <stdio.h>
// Function prototypes
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
float divide(int a, int b);
int main() {
int x = 10, y = 5;
printf("Sum: %d\n", add(x, y));
62 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
printf("Difference: %d\n", subtract(x, y));
printf("Product: %d\n", multiply(x, y));
printf("Quotient: %.2f\n", divide(x, y));
return 0;
}
// Function definitions
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
float divide(int a, int b) {
if (b != 0) return (float)a / b;
else { printf("Error: Division by zero\n"); return 0; }
}
Checklist
63 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Indicative content 2.6: Applications of Arrays
Duration: 5 hrs
Key steps:
Step 1: Introduce the activity and request learners to respond to the following questions:
Points to Remember
Arrays in c Programming:
In C programming, arrays are data structures that store multiple elements of the same type
in contiguous memory. The types of arrays include:
• One-Dimensional Array: A single row of elements. Declared with one pair of square
brackets.
64 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
• Two-Dimensional Array: An array of arrays, forming a matrix. Declared with two
pairs of square brackets for rows and columns.
Key steps:
Step 1: Introduce the topic and ask learners to perform tasks described below:
You are a teacher managing a class of students. You need to store the grades of
your students in a program so you can easily calculate averages, find the highest
and lowest grades, and perform other analyses.
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Ask trainees to discuss by writing the syntax declaration of arrays.
Step 4: Ask trainees to write the code in a given syntax of arrays
Step 5: Ask trainees to present their finding to the class.
Step 6: Ask trainees to ask clarification where necessary.
Step 7: Ask trainees to read key reading 2.6.2. Trainee Manual
65 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Points to Remember
Arrays declaration in c
In C programming, arrays are declared by specifying the data type of the elements and the
array size. The methods of declaration vary based on the array type:
• One-Dimensional Array:
data_typearray_name[array_size];
• Two-Dimensional Array:
data_typearray_name[rows][columns];
Key steps:
Step 1: Introduce the topic and ask learners to perform tasks described below:
You are a teacher managing a class of students. You need to store the grades of
your students in a program so you can easily calculate averages, find the highest
and lowest grades, and perform other analyses.
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Ask trainees to discuss by writing the code for array initialization.
Step 4: Ask trainees to write the code in a given syntax of arrays
Step 5: Ask trainees to present their finding to the class.
Step 6: Ask trainees to ask clarification where necessary.
Step 7: Ask trainees to read key reading 2.6.3 Trainee Manual
66 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Points to Remember
Array initialization in C
The general syntax for initializing an array during its declaration is as follows:
• data_type: The type of elements in the array (e.g., int, float, char).
• array_name: The name you give to the array.
• array_size: The number of elements the array can hold. This can sometimes be
omitted if the array is being initialized with values.
• {value1, value2, value3, ...}: A comma-separated list of values used to initialize the
array elements.
You are a software developer working on a sales analysis application for a retail store in
Kigali city. You need to record the sales figures for each day of the week and then calculate
the total and average sales. To achieve this, you will declare and initialize an array with the
sales data for the week.
Declare and initialize an array to store the daily sales figures for a week (7 days) and then
calculate and display the total and average sales.
Solution:
#include <stdio.h>
int main() {
// Declare and initialize an array to store daily sales for a week
float sales[7] = {1500.75, 2000.50, 1750.25, 1900.60, 2100.30, 1800.90, 2200.10};
67 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
}
return 0;
68 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Indicative content 2.7: Solving of C Programming Problems
Duration: 5 hrs
Key steps:
Step 1: Introduce the topic and ask learners to perform tasks described below:
You are a systems analyst working for a bank. Your task is to design a flowchart for
the ATM withdrawal process to help developers understand the logic and steps
involved in the transaction. Create a flowchart that outlines the steps a user takes to
withdraw money from an ATM. The flowchart should include the following steps:
• Start
• Insert ATM card
• Enter PIN
• Validate PIN
• Select withdrawal option
• Enter withdrawal amount
• Check account balance
• Dispense cash if the balance is sufficient
• Display error message if the balance is insufficient
• End transaction and eject card
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Ask trainees to discuss by writing the findings in appropriate template.
Step 4: Ask trainees to draw a flowchart of a given scenario.
Step 5: Ask trainees to present their finding to the class.
Step 6: Ask trainees to ask clarification where necessary.
69 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Step 7: Ask trainees to read key reading 2.7.1. Trainee Manual
Points to Remember
Key steps:
While delivering this activity, pass through the following steps:
Step 1: Introduce the topic and ask learners to perform tasks described below:
You are a software developer tasked with creating a system for a school to
sort student grades. The system will take a list of student grades and sort
them in ascending order to help teachers quickly identify students'
performance levels. Design an algorithm that sorts a list of student grades in
ascending order
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Ask trainees to discuss by writing the pseudocode of the problem.
Step 4: Ask trainees to design an algorithm of a given scenario.
Step 5: Ask trainees to present their finding to the class.
Step 6: Ask trainees to ask clarification where necessary.
Step 7: Ask trainees to read key reading 2.7.2 Trainee Manual
Points to Remember
70 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Practical Activity 2.7.3: Write the C program to solve the problem
• The trainer may use small groups to write the c code of a given problem.
• Avail examples of c code.
Key steps:
While delivering this activity, pass through the following steps:
Step 1: Introduce the topic and ask learners to perform tasks described below:
You need to write a C program to find the median of a list of integers. The
median is defined as:
• The middle value in a sorted list if the list has an odd number of elements.
• The average of the two middle values in a sorted list if the list has an even
number of elements.
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Ask trainees to discuss by writing the pseudocode of the problem.
Step 4: Ask trainees to write the c code of a given scenario.
Step 5: Ask trainees to present their finding to the class.
Step 6: Ask trainees to ask clarification where necessary.
Step 7: Ask trainees to read key reading 2.7.3 Trainee Manual
Points to Remember
71 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Key steps:
While delivering this activity, pass through the following steps:
Step 1: Introduce the topic and ask learners to perform tasks described below:
You need to write comprehensive documentation for a C program that calculates
the factorial of a non-negative integer. The documentation should describe the
purpose of the program, how to use it, and provide details on its functionality,
input/output, and any relevant notes.
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Ask trainees to discuss how to write the documentation of a program.
Step 4: Ask trainees to write the documentation on a written program.
Step 5: Ask trainees to present their finding to the class.
Step 6: Ask trainees to ask clarification where necessary.
Step 7: Ask trainees to read key reading 2.7.4. Trainee Manual
Points to Remember
Documenting a program
• Program’s functionality, main purpose, and key features to provide readers with a
clear understanding of what the program achieves.
Usage Instructions
• Execution: Steps to run the program and description of any command-line options.
Input/Output Specifications
• Expected inputs and outputs: Details on the format and any validation rules for
inputs and outputs.
72 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Solution:
Documentation for the Celsius to Fahrenheit Conversion Program
• Title
Celsius to Fahrenheit Temperature Converter
• Description
This C program converts a temperature from Celsius to Fahrenheit. The user inputs a
temperature in Celsius, and the program computes the equivalent temperature in
Fahrenheit using the formula: F=C×95+32F = C \times \frac{9}{5} + 32F=C×59+32 where FFF
is the temperature in Fahrenheit and CCC is the temperature in Celsius. The program then
displays the converted temperature.
• Usage Instructions
✓ Compile the Program: Use a C compiler such as gcc to compile the source code:
gcc -o temp_convertertemp_converter.c
✓ Run the Program: Execute the compiled program:
./temp_converter
✓ Enter Input:
o When prompted, enter a temperature in Celsius.
✓ View Output:
o The program will display the equivalent temperature in Fahrenheit.
• Input/Output Specifications
✓ Input:
o A single floating-point number representing the temperature in Celsius. The
input should be a valid number.
✓ Output:
o The temperature in Fahrenheit, formatted to two decimal places.
• Function Descriptions
• float celsiusToFahrenheit(float celsius)
✓ Purpose: Converts a temperature from Celsius to Fahrenheit.
✓ Parameters:
▪ float celsius - The temperature in Celsius.
✓ Returns:
▪ float - The equivalent temperature in Fahrenheit.
• int main()
✓ Purpose: Entry point of the program. Manages user input, performs
conversion, and displays the result.
✓ Returns:
▪ 0 - Successful execution.
73 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Checklist
74 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Learning outcome 2 end assessment
Written assessment
A. var int x;
B. int x;
C. variable int x;
D. int x = var;
Answer: B. int x;
[Link] of the following is the correct way to include a header file in a C program?
A. #include "stdio.h"
B. include <stdio.h>
C. #include <stdio.h>
D. #include <stdio.h.h>
#include <stdio.h>
int main() {
int a = 10, b = 5;
printf("%d\n", a + b);
return 0;
}
A. 10
B. 15
C. 5
D. 105
Answer: B. 15
75 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
[Link] of the following data types can be used to store a floating-point number in C?
A. Int
B. Char
C. Float
D. bool
Answer: C. float
#include <stdio.h>
int main() {
int x = 7;
printf("%d\n", x % 3);
return 0;
}
A. 7
B. 2
C. 3
D. 1
Answer: D. 1
A. int arr[10];
B. int arr(10);
C. array int arr[10];
D. int arr = [10];
A. scanf()
B. printf()
C. input()
D. read()
Answer: A. scanf()
76 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
[Link] is the purpose of the return 0; statement in the main() function?
A. return_typefunction_name(parameters) { /* code */ }
B. function return_typefunction_name(parameters) { /* code */ }
C. function return_type { /* code */ } function_name(parameters)
D. function_name(parameters) return_type { /* code */ }
A. A reserved keyword
B. A block of code that performs a specific task
C. A type of data structure
D. A type of loop
A. int function_name[];
B. function_name int();
C. int function_name();
D. function_name = int();
A. void
B. return
C. break
D. exit
77 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Answer: B) return
A. loop
B. do-while
C. foreach
D. switch-case
Answer:B) do-while
int x = 5;
if (x > 3) {
printf("Hello");
} else {
printf("World");
A. World
B. Hello
C. Error
D. 5
Answer: B) Hello
15. Which control statement allows a program to execute a block of code repeatedly
based on a condition?
A. if
B. for
C. switch
D. goto
Answer:B) for
78 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
A. continue
B. break
C. return
D. switch
Answer:B) break
Answer:B) Skips the current iteration and continues with the next iteration
A. switch (variable) {}
B. if (variable) {}
C. loop (variable) {}
D. case (variable) {}
Subjective questions
1. Explain the difference between a for loop and a while loop in C. Provide examples of
when to use each.
Answer:A for loop is typically used when the number of iterations is known
beforehand. It includes initialization, a condition check, and an
increment/decrement in a single line. A while loop is used when the number of
79 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
iterations is not known, and it continues executing as long as a specified condition is
true.
Example:
printf("%d\n", i);
int n = 0;
while (n < 5) {
printf("%d\n", n);
n++;
Answer:
// Declaration
int numbers[5];
// Initialization
80 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
3. How does a switch statement work in C, and how does it differ from an if-else
statement? Illustrate with code examples.
Answer:
Example:
int choice = 2;
switch (choice) {
case 1:
printf("Choice is 1\n");
break;
case 2:
printf("Choice is 2\n");
break;
default:
printf("Invalid choice\n");
if (choice == 1) {
printf("Choice is 1\n");
} else if (choice == 2) {
printf("Choice is 2\n");
81 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
} else {
printf("Invalid choice\n");
4. Describe the purpose of the break and continue statements in loops. Provide
examples of how each is used.
Answer
The break statement is used to terminate the loop immediately, regardless of the
condition. The continue statement skips the rest of the code inside the loop for the
current iteration and moves to the next iteration.
Examples:
// Break example
if (i == 3) {
printf("%d\n", i);
// Continue example
if (i == 3) {
printf("%d\n", i);
82 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
}
break is used when a certain condition needs to stop the loop, while continue is used
to skip specific iterations without ending the loop.
5. Write a C program to find the largest number in an array of integers. Explain the logic
used in your solution.
Answer:
#include <stdio.h>
int main() {
max = arr[i];
return 0;
6. What are nested loops, and when are they used in C programming? Provide an
example of a situation where nested loops would be necessary.
Answer:
83 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Nested loops are loops inside other loops. They are used when performing
operations on multi-dimensional data structures or when a repetitive task needs to
occur within another repetitive task.
printf("* ");
printf("\n");
Here, the outer loop controls the rows, and the inner loop controls the columns,
printing a 5x5 grid of *.
7. Discuss the concept of an infinite loop. How can an infinite loop be created in C, and
how can it be terminated?
Answer:
An infinite loop is a loop that continues indefinitely because the condition never
becomes false. It can be created using a while or for loop without a termination
condition.
Example:
while (1) {
84 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Answer:
Multidimensional arrays are arrays with more than one dimension. A common
example is a 2D array, which is used to represent matrices or tables.
Example:
// Accessing elements
Here, matrix is a 2x3 array storing integers. Elements are accessed using two indices:
the row and column.
9. What are the limitations of using arrays in C? How do arrays differ from other data
structures like linked lists?
Answer:
Limitations of Arrays:
• Arrays provide fast access using index, while linked lists allow dynamic resizing and
efficient insertion/deletion.
• Arrays use contiguous memory; linked lists use scattered memory locations with
pointers connecting elements.
85 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Practical assessment
1. Write a C program to find the sum of all integers from 1 to n, where n is provided by the
user.
Answer:
#include <stdio.h>
int main() {
int n, sum = 0;
// Prompt user for input
printf("Enter a positive integer: ");
scanf("%d", &n);
// Calculate the sum
for (int i = 1; i<= n; i++) {
sum += i;
}
// Display the result
printf("The sum of all integers from 1 to %d is %d\n", n, sum);
return 0;
}
Checklist
86 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
bool isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i * i<= num; i++) {
if (num % i == 0) return false;
}
return true;
}
int main() {
int num;
// Prompt user for input
printf("Enter a positive integer: ");
scanf("%d", &num);
// Check if the number is prime
if (isPrime(num)) {
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}
return 0;
}
Checklist/solution for application
87 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
3. Write a C program to reverse a string entered by the user.
Answer:
#include <stdio.h>
#include <string.h>
int main() {
char str[100], reversed[100];
int length, i, j;
// Prompt user for input
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0'; // Remove newline character if present
length = strlen(str);
j = 0;
// Reverse the string
for (i = length - 1; i>= 0; i--) {
reversed[j++] = str[i];
}
reversed[j] = '\0';
// Display the reversed string
printf("Reversed string: %s\n", reversed);
return 0;
}
Checklist/solution for application
88 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
4. Write a C program to calculate the factorial of a non-negative integer using recursion.
Answer:
#include <stdio.h>
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
int main() {
int num;
// Prompt user for input
printf("Enter a non-negative integer: ");
scanf("%d", &num);
if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
printf("Factorial of %d is %d\n", num, factorial(num));
}
return 0;
}
Checklist/solution for application
89 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
5. Write a C program to find the largest and smallest number in an array of integers.
Answer:
#include <stdio.h>
int main() {
int n;
// Prompt user for number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
int i, largest, smallest;
// Prompt user to enter the array elements
printf("Enter %d integers:\n", n);
for (i = 0; i< n; i++) {
scanf("%d", &arr[i]);
}
largest = smallest = arr[0];
// Find the largest and smallest numbers
for (i = 1; i< n; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
if (arr[i] < smallest) {
smallest = arr[i];
}
}
// Display the results
printf("Largest number: %d\n", largest);
printf("Smallest number: %d\n", smallest);
return 0;}
Checklist/solution for application
90 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
SN CRITERIA INDICATORS YES NO
1. The array is 1.1. Prompt user for number of
correctly sorted elements is displayed
1.2. Prompt user to enter the
array elements is displayed
1.3. The loop to find the greatest
number is mentioned
1.4. The results is displayed
6. Write a C program to sort an array of integers in ascending order using the bubble sort
algorithm.
Answer:
#include <stdio.h>
void bubbleSort(int arr[], int n) {
for (int i = 0; i< n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] >arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int n;
// Prompt user for number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
// Prompt user to enter the array elements
91 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
printf("Enter %d integers:\n", n);
for (int i = 0; i< n; i++) {
scanf("%d", &arr[i]);
}
92 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Further information to the trainer
A. Books
Graham, D. L. (2019). C Programming Language: A Step by Step Beginner's Guide to Learn C
Programming. Amazon.
B. Websites
[Link]
and-flowchart/.
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
c#:~:text=Array%20in%20C%20can%20be,data%20types%20too%20like%20structures.
[Link]
[Link]
[Link]
93 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Learning Outcome 3: Perform Program Debugging
94 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Indicative contents
95 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Duration: 10hrs
By the end of the learning outcome, the trainees will be able to:
Resources
Advance Preparation:
96 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Indicative content 3.1: Identification of Errors
Duration: 5 hrs
● Trainer may small groups may be used to describe the types of errors.
● Avail examples of written algorithms to describe types of arrays.
Key steps:
Step 1: Introduce the activity and request learners to respond to the following questions:
i. What is an error in c programming?
ii. How to read an error in c programming?
iii. What are the different types of errors?
Step 2: Monitor the discussion and asks trainees to write the findings on paper
Step 3: Ask trainees to present their findings to the whole class.
Step 4: Provide an expert view and relate it to what they presented.
Step 5: Address any questions or concerns.
Step 6: Orient them to read the key reading 3.1.1
Points to Remember
In C programming, an error refers to any deviation from the intended or expected behavior
of a program. Errors can occur at various stages of development and execution and are
categorized into three main types: syntax errors, logical errors, and runtime errors.
• Syntax Errors:
✓ Violations of the rules of the C programming language. They occur when the
code does not conform to the syntax of C.
• Logical Errors:
97 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
✓ Flaws in the logic or design of a program, leading to undesired outcomes or
• Runtime Errors:
Key steps:
Step 1: Introduce the topic and ask learners to perform tasks described below:
In your computer lab, suppose that you're working on a simple C program that
reads a series of numbers from the user, calculates their sum, and then displays
the result. However, there are several errors in the code, and your task is to
identify practical techniques for correcting errors and correct them.
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Demonstrate how to do the given tasks by identifying the founded errors.
Step 4: Demonstrating, how to correct errors.
Step 5: Compile for checking if errors are corrected according to the finding answers.
Step 6: Ask trainees to read keyreading 3.1.2
Points to Remember
98 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
• Divide and Conquer
You are an engineer working on an embedded system project for a weather monitoring
station. The station collects temperature readings from multiple sensors installed in
different locations (e.g., on different floors of a building or at various points in a large area).
Your task is identify the errors in the segment of code.
#include <stdio.h>
int main() {
return 0;
Task:
Answer:
Error:
The error in the code is found in the for-loop condition:
99 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
The loop iterates while i is less than or equal to 5. Since array indices in C are zero-based,
valid indices for arr range from 0 to 4 (5 elements in total). However, the condition i<= 5
allows i to take the value 5, which is an out-of-bounds index for arr.
When i becomes 5, the code attempts to access arr[5], which does not exist in the array.
Accessing an out-of-bounds element in an array leads to undefined behavior, which can
cause the program to crash, produce incorrect results, or access unintended memory.
Correction:
To prevent the program from accessing out-of-bounds memory, you should change the loop
condition so that i only ranges from 0 to 4, which are the valid indices for the array arr. The
corrected loop should be:
Corrected Code:
#include <stdio.h>
int main() {
return 0;
100 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Checklist/solution for application
101 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Indicative content 3.2: Compilation of the C Program
Duration: 3 hrs
Key steps:
Step 1: Introduce the activity and request learners to respond to the following questions:
i. What is a compiler?
ii. What does the compiler do exactly?
iii. identify the different types of compilers
Step 2: Monitor the discussion and asks trainees to write the findings on paper
Step 3: Ask trainees to present their findings to the whole class.
Step 4: Provide an expert view and relate it to what they presented.
Step 5: Address any questions or concerns.
Step 6: Orient them to read the key reading
Points to Remember
What is a Compiler?
A compiler is software that converts high-level programming language code (like C) into
machine-level language. It checks the code for errors and reports them if the code does not
follow language rules.
Types of Compilers:
• Borland Turbo C: A basic, fast C compiler known for its small size, re-released as
freeware in 2006.
• Tiny C Compiler (TCC): Optimized for slow computers with limited disk space, known
for its small size and fast compilation speed.
102 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
• Portable C Compiler (PCC): An influential compiler from the mid-1970s, designed for
portability and error checking with machine-dependent source files.
• GCC (GNU Compiler Collection): Supports multiple languages, initially released for C,
and known for extensive optimizations like dead code elimination.
Key steps:
Step 1: Introduce the topic and ask learners to perform tasks described below:
Compile and run a simple C program that prints "Hello, World!" to the console.
Step 2: Explain the task and provide clear work instruction (Task, Time allocated)
Step 3: Ask trainees to write the source code.
Step 4: Ask trainees to open terminal/command prompt
Step 5: Ask trainees to Compile the Program
Step 6: Repeat the whole process to be clear and concise
Step 7: Ask trainees to read keyreading 3.2.2
Points to Remember
Compilation techniques
103 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
• Semantic Analysis: Verifies the meaning and correctness of the code, performing
type checking and enforcing semantic rules.
A parser is responsible for checking the syntactic structure of the code according to the rules
of the programming language. Consider the following code snippet:
if (x > 0 {
printf("Positive");
Task:
1. Identify the syntax error in the code and explain why it would be flagged by the
parser.
2. How does a parser use a parse tree or abstract syntax tree (AST) to represent the
structure of this code?
Answer:
if (x > 0 {
printf("Positive");
A parser uses a parse tree or an abstract syntax tree (AST) to represent the syntactic
structure of the code.
• Parse Tree: A parse tree represents the hierarchical structure of the code based on
the grammar of the programming language. Each node in the parse tree corresponds
to a grammatical construct (e.g., expressions, statements), and the tree is built
according to the rules of the language. The parse tree is usually more detailed,
reflecting the precise syntactic structure, including all symbols like parentheses.
• Abstract Syntax Tree (AST): An AST is a simplified version of the parse tree, where
certain syntactic details are omitted to focus on the essential structure of the code.
104 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
It abstracts away some of the grammatical rules, leaving only the essential
components like operators, operands, and control structures.
if (x > 0) {
printf("Positive");
Checklist
105 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Indicative content 3.3: Test of the C Program
Duration: 2 hrs
Key steps:
Step 1:Introduce the topic and ask learners to perform tasks described below:
Write a c program to display a simple calculator and write all possible test cases of
this program.
Step 2: Ask trainees to discuss on the given tasks in their groups.
Step 3: Ask trainees to write down the finding from the discussion.
Step 4: Ask trainees to present the findings.
Step 5: Ask clarification if any.
Step 6: Ask trainees to read the key reading 3.3.1
Points to Remember
106 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
● Postconditions: Describe the state after the test has been
executed.
Key steps:
Step 1: Introduce the topic and ask learners to perform tasks described below:
Write a c program to find the factorial of a number, you are requested to identify the
debugging techniques you have used.
Step 2: Ask trainees to Write the source code of a given scenario in their groups
Step 3: Ask trainees to compile the written source code
Step 4: Ask trainees to debug the founded bugs if any
Step 5: Read the key reading 3.3.2
Points to Remember
Debugging Techniques:
● Print Debugging: Use print statements to display variable values and program
flow.
● Debugger Tools: Utilize tools like GDB or IDE features to set breakpoints, step
through code, and inspect variables.
● Breakpoints: Pause execution at specific points to inspect variables and program
state.
● Watch and Evaluate Expressions: Monitor and evaluate variable values or
expressions during execution.
107 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Application of learning 3.3.
You have opened a savings account at a local bank, and you want to know how much
interest you will earn over a certain period. The bank offers a simple interest rate of 5% per
year. You decide to write a C program to calculate the interest you will earn based on the
amount of money (principal) you deposit, the interest rate, and the time period in [Link]
this task, please complete the following:
Checklist
108 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Learning outcome 3 end assessment
Written assessment
A) Runtime error
B) Logical error
C) Syntax error
D) Semantic error
3. Which type of error is the most difficult to detect and fix because the program still
runs but gives incorrect output?
A) Compilation error
B) Logical error
C) Syntax error
D) Semantic error
4. What type of error will the following code produce? printf("Hello World)
A) Syntax error
B) Runtime error
109 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
C) Logical error
2. Compilation Techniques
A) Linking
B) Preprocessing
C) Code Optimization
D) Assembling
Answer: B) Preprocessing
7. Which compilation technique translates high-level code into machine code one line
at a time, while the program is running?
A) Interpreter
B) Compiler
C) Assembler
D) Linker
Answer: A) Interpreter
A) Linking
B) Preprocessing
C) Assembling
D) Optimization
110 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Answer: C) Assembling
3. Debugging Tools
9. Which of the following tools is commonly used for debugging C programs on Unix-
like systems?
A) Valgrind
B) Git
C) NetBeans
D) Makefile
Answer: A) Valgrind
11. Which debugging tool allows you to step through your program line-by-line to
check its execution flow?
A. Compiler
B. Debugger
C. Profiler
D. Assembler
Answer: B) Debugger
12. Which of the following is NOT a feature of most modern debugging tools?
A) Breakpoints
13. Which tool is used to analyze memory management problems, like memory leaks
and invalid memory access in C programs?
111 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
B) GCC (GNU Compiler Collection)
C) Valgrind
D) Make
Answer: C) Valgrind
14. What is the main use of setting breakpoints while debugging a program?
Subjective questions
1. What is the purpose of a compiler in the context of C programming?
Answer: A compiler in C programming translates source code written in the high-level C
language into machine code or lower-level code that the computer's processor can execute.
It checks the code for syntax and semantic errors, performs optimizations, and generates an
executable file.
2. Describe the main phases of the compilation process in C programming.
Answer: The main phases of the C compilation process are:
1. Preprocessing: Handles preprocessor directives (e.g., #include, #define) and
prepares the code for compilation by performing text substitution and macro
expansion.
2. Lexical Analysis: Breaks down the source code into tokens, which are the smallest
units of meaning (keywords, identifiers, operators, etc.).
3. Syntax Analysis:Analyzes the tokens to ensure they follow the syntax rules of the
language and constructs a parse tree or abstract syntax tree (AST) representing the
code's structure.
4. Semantic Analysis: Ensures that the code makes logical sense, checking for type
consistency, valid variable declarations, and correct function calls.
5. Intermediate Code Generation: Produces an intermediate representation of the
code, which is platform-independent and easier to optimize.
6. Optimization: Applies various techniques to improve the efficiency of the generated
code, such as eliminating dead code or optimizing loops.
112 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
7. Code Generation: Translates the intermediate code into machine code or assembly
language specific to the target architecture.
8. Linking: Combines multiple object files and libraries into a single executable,
resolving references between different modules and external libraries.
3. What is the role of a linker in the C compilation process?
Answer: The linker combines multiple object files and libraries into a single executable file. It
resolves references between different parts of the program, such as function calls and
variable accesses, and ensures that all code and data are properly linked together. The linker
also handles the inclusion of external libraries and addresses any inter-module
dependencies.
4. Explain the difference between syntax errors and semantic errors in C programming.
Answer:
• Syntax Errors: These occur when the code violates the grammatical rules of the C
language. Examples include missing semicolons, unmatched parentheses, or
incorrect keyword usage. Syntax errors are usually detected during the compilation
phase and prevent the code from being compiled.
• Semantic Errors: These occur when the code is syntactically correct but semantically
incorrect, meaning it does not make logical sense. Examples include type
mismatches, invalid function calls, or incorrect use of variables. Semantic errors are
usually detected during the semantic analysis phase of compilation.
5. What is the purpose of the #include directive in a C program?
Answer: The #include directive is used to include the contents of a specified file into the
source code file before compilation. It is commonly used to include standard library headers
or user-defined header files. This directive allows the program to use functions, macros, and
definitions declared in the included files.
6. How does optimization improve the performance of a compiled C program?
Answer: Optimization improves the performance of a compiled C program by applying
various techniques to make the code more efficient. These techniques can include:
• Dead Code Elimination: Removing code that does not affect the program's outcome.
• Loop Unrolling: Reducing the number of iterations by increasing the number of
operations within a loop.
• Constant Folding: Evaluating constant expressions at compile time rather than
runtime.
• Inlining: Replacing function calls with the actual function code to reduce the
overhead of function calls.
113 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
These optimizations can lead to faster execution, reduced memory usage, and overall
improved performance of the program.
7. What is the significance of the main function in a C program?
Answer: The main function is the entry point of a C program. It is where the execution of the
program begins. Every C program must have a main function, and it typically returns an
integer value indicating the success or failure of the program's execution. The main function
can also take command-line arguments, which can be used to provide input to the program
at runtime.
8. What is a preprocessor directive, and provide an example?
Answer: A preprocessor directive is a command that is processed by the C preprocessor
before the actual compilation of the code begins. Preprocessor directives are used to
include files, define macros, and conditionally compile code. An example of a preprocessor
directive is #define, which is used to create macros:
#define PI 3.14159
This directive defines a constant PI with the value 3.14159, which can be used throughout
the code wherever PI is referenced.
Practical assessment
Checklist
114 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
C Program:
#include<stdio.h>
intmain() {
int length, width;
printf("Enter the length of the rectangle: ");
scanf("%d", &length);
printf("Enter the width of the rectangle: ");
scanf("%d", &width);
return0;
}
Answer:
To compile the given C program, use a C compiler such as gcc. Open a terminal and navigate
to the directory where the C program file (e.g., rectangle.c) is located. Run the following
command:
Here, gcc is the compiler command, -o rectangle specifies the name of the output
executable file, and rectangle.c is the source code file.
In this case, the provided program is straightforward and should compile without errors.
However, let's discuss possible issues that might occur in a similar scenario:
• Syntax Errors: If there were any syntax errors (e.g., missing semicolons or incorrect
syntax), the compiler would display an error message indicating the line number and
the nature of the error. For example, a missing semicolon after the printf statement
would generate an error like:
115 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
return0;
• Warnings: The compiler might produce warnings if there are potential issues that do
not stop compilation but could lead to runtime problems. For instance, using scanf
with %d requires valid integer input. A warning might occur if improper format
specifiers are used.
Checklist
116 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
• Linking: If necessary, the compiler links the object code with libraries to create the
final executable. In this simple example, there are no additional libraries to link, so
the executable is created directly.
• Executable Output: The gcc command generates an executable file named rectangle.
You can run this file to execute the program.
Checklist
END
117 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
Further information to the trainer
A. Books
Graham, D. L. (2019). C Programming Language: A Step by Step Beginner's Guide to Learn C
Programming. Amazon.
B. Websites
[Link]
VpZD0wMTU4N2M4NC03NWVlLTZlOWItMzIwYS02ZjQ0NzQ2YzZmM2EmaW5zaWQ9NTE5O
A&ptn=3&ver=2&hsh=3&fclid=01587c84-75ee-6e9b-320a-
6f44746c6f3a&psq=scenario+application+of+learning+of+debugging+c+programming&u=a1
aHR0cHM6Ly9jcy5icm93bi5lZHUvY291cnNlcy9jc2NpMTMxMC8yMDIwL2Fzc2lnbi9sYWJzL2x
hYjEuaHRtbA&ntb=1
[Link]
[Link]
[Link]
[Link]
d&q=common+debugging+techniques+and+tools+you+can+use+when+working+with+C+pr
ogramming
118 | C P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e r M a n u a l
October,2024
Mm, YYY
119 | M o d u l e t i t l e – T r a i n e r M a n u a l