Basic Computer Lab Module 2024/2025, Algorithms and Programming English Edition
Basic Computer Lab Module 2024/2025, Algorithms and Programming English Edition
Praise to our prayers for the presence of God Almighty, All-Compassionate and
Merciful, because of His grace and guidance, Algorithms and Programming Practicum
Module can be completed.
On this occasion, we would like to thank all parties who have contributed, so that
the Algorithm and Programming Practical Module can be published.
We really hope for criticism and suggestions for future improvements. Hopefully this
book can be useful for readers. Happy reading and doing the practicum.
Compiler team
Member :
NIP : 14890058
Hereby declare that all the information in this module has been reviewed and will be used as
the main course material supplement for the practicum that will be held on the second
semester of 2024/2025 term at Laboratorium Dasar Komputer, School of Electrical
Engineering, Telkom University.
LETTER OF REVISION
VISION:
To become an internationally reputable faculty that excels in education, research, and innovation
and entrepreneurship in the disciplines of electrical and physical engineering that contribute to the
achievement of sustainable development goals
MISSION:
1. Organizing an international standard education system in the field of engineering and
physical engineering with an entrepreneurial outlook.
2. Develop and disseminate new knowledge and intellectual products in the field of
engineering and physical engineering that contribute to the fulfillment of sustainable
development goals.
3. Generate innovations through collaboration with industry and other stakeholders that
contribute to the nation's economic growth.
OBJECTIVES:
1. Producing graduates with global competitiveness and entrepreneurial insight.
2. Producing research that contributes to the needs of the nation and the world through
the creation of new knowledge and intellectual products to meet sustainable
development goals.
3. Producing intellectual products and innovations that contribute to the nation's progress
and sustainable development growth.
b. Second Condition
Algorithm and Programming Practical Module 2024/2025
vii
The practicum course that consists of 3-4 practical subjects, with 2 or 3 prakticum
module:
• Students are required to attend all practical meetings.
• If you do not follow the provisions above, the grade for the practical course
will be E.
3. Grade complaints on certain modules are only accommodated in the relevant
module week and a maximum of the 16th week of lectures.
4. For students who repeat the practicum, it is mandatory to confirm the grades for
the practicum subjects that they passed in the previous year to the laboratory
assistant during the grade validation period.
A. Students who take part in practical work (internships) at the Faculty of Electrical
Engineering are required to follow the rules of the Faculty of Electrical Engineering
and each related laboratory and comply with the sanctions that have been set.
B. The requirements for applying for a follow-up practical permit only apply to those
who meet the following criteria:
1. Sick
a. Hospitalized
• Practitioners are required to attach a certificate of inpatient care from the
hospital/health center/related agency.
• Practitioners are required to process applications for follow-up practicums
a maximum of seven days after the inpatient period has finished.
b. Chronic Disease
Practitioners are required to attach a sick note from a hospital/health
center/related agency and provide evidence of medical records showing that the
illness has been suffered for a long period of time.
c. Outpatient
• Practitioners in the Bandung area and its surroundings are required to
attach a certificate from a doctor from “Telkomedika Kampus” stating that
they are sick and need to rest.
• Practitioners who are outside the Bandung area are required to provide a
letter stating that they are sick and need rest from the doctor treating them,
and attach photo evidence of the prescription and administration.
• Practitioners are not permitted to attach a medical certificate from an online
clinic/doctor.
• Practitioners are only given the opportunity to attach a sick letter from a
clinic other than Telkomedika Campus, a maximum of once to apply for a
follow-up practicum in each practicum subject.
3. Disaster
a. Death of the Nuclear Family
• Practitioners are required to attach a death certificate no later than seven days
after the incident occurred. Nuclear family consists of parents, older siblings,
and younger siblings.
b. Accident
• Practitioners are advised to document the scene of the incident/other related
accident evidence as evidence for submitting a follow-up practicum.
• Practitioners who do not have time to document the scene of the crime/other
evidence of the accident are required to make a stamped statement
accompanied by a statement of confirmation from an authorized party around
the scene of the crime.
4. Worship
Interns are required to attach a copy of the proof of approval of the dispensation
from i-Gracias which has been approved by the Student Affairs Body.
D. The decision regarding the submission of follow-up practicums in point C by the FTE
Laboratory Assistant as a representative of the Faculty of Electrical Engineering is
absolute and cannot be contested.
In order to realize safety and comfort during the practicum, the participation of all
practicum participants and assistants is required. Therefore, compliance and order of each
individual towards the following safety guidelines are required:
A. Ergonomics
1. Correct body position
• Head and neck section
A good head and neck position is upright with a straight view. With this position,
the practitioner will be able to last longer in front of the computer and will not get
tired quickly. A neck position that is too flexible and the head tilted or lowered
when facing the monitor is not allowed because it will get tired quickly.
• Back part
Sitting with a straight and relaxed back is the correct position when using a
computer. A body that is too bent, tilted too far to the left or right, can cause pain.
Try to keep your entire back well supported by the back of the chair.
• Shoulder part
Position your shoulders so that your shoulder muscles are not tense. Try not to
keep your shoulders too low or too high.
• Arm and elbow position
A good arm position is at the side of the body and the elbow forms an angle
greater than 90 degrees.
2. Monitor position
• Place the monitor in a room with sufficient lighting (not too bright and not too
dim).
• Adjust the monitor position so that it is directly in front of your eyes with an ideal
distance from your eyes to the computer of 30 cm.
• Adjust the monitor brightness so that the light coming out is not too bright or too
dim.
3. Mouse usage
The correct position of the mouse is next to the keyboard. Adjust the hand that is
usually used to work. If the practitioner works with the left hand, place the mouse to
the left of the keyboard and set the mouse setting to left-handed through the
operating system. Use of the mouse when using the mouse, try to keep the wrist in a
position that is not hanging or lower than the mouse.
Algorithm and Programming Practical Module 2024/2025
xiii
4. Keyboard usage
• Align your wrist with your palm. Try to keep your wrist aligned with your palm.
Relax your wrist as if it were floating.
• Hanging elbow position. Make sure your elbows are in a free hanging position.
Leaning your elbows on the back of the chair while typing, besides making it
difficult to type, also makes you tense and tired quickly.
• Relax your index finger and ring finger. The key to typing without getting tired is
to relax all your fingers. Don't be stiff and tense. Let them be limp, relaxed, as they
are.
• Press the keyboard keys calmly. Do not press the keys hard or apply full force to
the hand.
• When not typing, relax your entire hand when not pressing the keys on the
keyboard. The condition before typing also affects the condition when typing.
7. Position of cables
Arrange the cables neatly and properly. Check the power outlet or power source, make
sure nothing is loose because unstable electricity can potentially damage computer
hardware and cause short circuits.
The most common electrical hazard accident is electric shock. Here are the things that
practitioners should follow if this happens:
• Do not panic,
• Turn off all electronic equipment and power sources on each desk and on the desk
of the practitioner who is exposed to electric current,
• Help the practitioner who has been electrocuted to remove himself from the
power source,
• Inform and ask for help from assistants, other practitioners and people around you
about accidents caused by electrical hazards.
• Fire
Fire Prevention
Fire prevention includes:
1. Store flammable materials in a safe place away from sources of ignition.
2. Combustible materials such as paper must not be stored in the server room f
3. Don't let trash (for example unused paper) pile up and burn it in random places.
4. Make sure that cables and electrical equipment are not damaged.
5. Do not overload the electrical circuit.
6. Smoking is prohibited in the laboratory.
Firefighter
If a fire occurs, immediately take the following steps:
1. Keep Calm and Don't Panic
INTRODUCTION................................................................................................................................................................................... i
ALGORITHM AND PROGRAMMING PRACTICUM MODULE WRITING TEAM .................................................................. ii
LETTER OF STATEMENT .................................................................................................................................................................. iii
LETTER OF REVISION........................................................................................................................................................................ iv
VISION, MISSION AND OBJECTIVES OF THE FACULTY OF ELECTRICAL ENGINEERING ............................................. v
IMPLEMENTATION OF PRACTICUM ACTIVITIES ...................................................................................................................... vi
EVEN SEMESTER OF ACADEMIC YEAR 2024/2025 FACULTY OF ELECTRICAL ENGINEERING .................................. vi
RULES FOR FOLLOW-UP PRACTICUM ........................................................................................................................................ ix
LABORATORY RULES........................................................................................................................................................................ xi
LAB LOCATION PLAN ..................................................................................................................................................................... xii
GENERAL GUIDELINES FOR SAFETY AND USE OF LABORATORY EQUIPMENT .......................................................... xiii
LIST OF CONTENTS ....................................................................................................................................................................... xvii
DASKOM LABORATORY PRACTICUM ASSISTANT 2024/2025 .......................................................................................... xix
MODULE 1: INTRODUCTION TO ALGORITHM AND PROGRAMMING .............................................................................. 1
1.1 Integrated Development Environment (IDE) ......................................................................................................................... 1
1.2 Visual Studio Code Installation ................................................................................................................................................ 2
1.3 Creating Simple Code ................................................................................................................................................................ 8
1.4 Algorithm .......................................................................................................................................................................................11
1.5 Basic Structure of C Programming ........................................................................................................................................ 14
1.6 Debugging ................................................................................................................................................................................... 17
MODULE 2: BASIC SYNTAX AND STRUCTURE OF C PROGRAMS ..................................................................................... 19
2.1 Variables and Constants ........................................................................................................................................................... 19
2.2 Data Types .................................................................................................................................................................................. 22
2.3 Arithmetic Operations ............................................................................................................................................................. 23
2.4 Struct ............................................................................................................................................................................................ 25
MODULE 3: PROGRAM FLOW CONTROL ............................................................................................................................... 28
3.1 Logical and Relational .............................................................................................................................................................. 28
3.2 If – Else ......................................................................................................................................................................................... 29
3.3 Switch Case................................................................................................................................................................................. 32
MODULE 4: LOOPING AND ITERATION................................................................................................................................... 34
4.1 Repetition..................................................................................................................................................................................... 34
4.2 Types of Looping ...................................................................................................................................................................... 35
4.3 Control Commands.................................................................................................................................................................. 40
MODULE 5 : FUNCTIONS ............................................................................................................................................................... 41
5.1 Standard Library Functions ...................................................................................................................................................... 41
5.2 Functions ..................................................................................................................................................................................... 42
Algorithm and Programming Practical Module 2024/2025
xvii
5.3 Void Function/Procedure (Void Function) ......................................................................................................................... 45
5.4 Recursive Algorithms ............................................................................................................................................................... 45
MODULE 6: ARRAYS AND STRINGS .......................................................................................................................................... 47
6.1 Array .............................................................................................................................................................................................. 47
6.2 One Dimensional Array ........................................................................................................................................................... 49
6.3 Multidimensional Arrays .......................................................................................................................................................... 51
6.4 String ............................................................................................................................................................................................ 53
MODULE 7 : SORTING ................................................................................................................................................................... 64
7.1 Selection Sort .............................................................................................................................................................................. 64
7.2 Insertion Sort .............................................................................................................................................................................. 68
7.3 Bubble Sort .................................................................................................................................................................................. 71
MODULE 8 : SEARCHING .............................................................................................................................................................. 74
8.1 Sequential Search ...................................................................................................................................................................... 74
8.2 Binary Search ............................................................................................................................................................................. 77
MODULE 9 : POINTER .................................................................................................................................................................... 80
9.1 Understanding Pointer ............................................................................................................................................................. 80
9.2 Pointer Operators ..................................................................................................................................................................... 83
9.3 Void Pointer ............................................................................................................................................................................... 84
9.4 Pointer and Array ..................................................................................................................................................................... 84
9.5 Arithmetic Operations On Pointer ....................................................................................................................................... 86
9.6 Pointer and String..................................................................................................................................................................... 87
9.7 Pointer As Function Parameters ........................................................................................................................................... 88
9.8 Pointers with Structs................................................................................................................................................................. 88
9.9 Malloc and Free Functions ...................................................................................................................................................... 91
MODULE 10 : FILE INPUT/OUTPUT............................................................................................................................................. 92
10.1 Understanding Input/Output Files ...................................................................................................................................... 92
10.2 Opening Files ........................................................................................................................................................................... 93
10.3 Processing Files ........................................................................................................................................................................ 94
10.4 Closing Files .............................................................................................................................................................................107
10.5 Additions.................................................................................................................................................................................. 108
BASIC TECHNICAL REPORT WRITING ..................................................................................................................................... 109
BIBLIOGRAPHY ................................................................................................................................................................................ 114
Assistant
No. NIM Name Position Phone Number Line ID
Code
patrianand
1. 1102223051 Teguh Patriananda TGH Assistant coordinator 087885538877
ateguh
natashafba
3. 1101223205 Natasha Fedora Barus NFB Admin I 081232644668
rus
8. 1101223083 Aliza Nurfitrian Meizahra ALL Responsible for Software 082240482882 alizaaja24
Person in Charge of SC
9. 1101223078 Alika Widuri Kartika AKA Division Assignment and 081910346047 alikaawk
Task Committee (ATC)
Person in Charge of SC
Creative Media laukemas3
10. 1105220065 Riza Aria Komara RIZ 087830350963
Development (CMD) 35
Division
Person in Charge of SC
Human Resource
11. 1104223057 Farhan Oktavian IAN 085861090100 me.ahan
Development (HRD)
Division
Person in Charge of SC
12. 1105223068 Darla Gempita Darris Purba DAR Maintenance and Logistics 088263589854 darlaoreki
Committee (MLC) Division
Person in Charge of SC
cindy.sriasti
13. 1102223133 Ni Kadek Cindy Sriastiti CYN Division Rules and 0895394594943
ti
Discipline Committee (RDC)
Daskom Dev Community
14. 1104220015 Junaidi Rahmat JIN 082292625290 hyakkimaru
(DDC) Division Team
Daskom Dev Community
15. 1104220063 Muh Zaidan Fauzan FYN 082123870889 ea____
(DDC) Division Team
Daskom Dev Community diarcwanto
16. 1101224329 Dhiya Isnavisa DHY 085213696428
(DDC) Division Team fly
Nur Muhammad Faza Dwi SC Division Assignment
17. 1104223009 FAZ 082243519148 fxfyfaza
Fajar Ramdhani and Task Committee (ATC)
18. 1102223024 Justin Fairman Tan JFT SC Division Assignment 081277991505 justinft
SC Division Assignment
19. 1102223233 Muhammad Ferdiansyah PER 081293393183 frtwinz
and Task Committee (ATC)
SC Division Assignment a_s_r_rbahr
20. 1101224317 Ahmad Syaiful Bahri BRI 081217028937
and Task Committee (ATC) i
SC Creative Media
21. 1105223102 Cantik Zelda Herawan EZL Development (CMD) 085759066922 cantik_zldh
Division
SC Creative Media
Muhammad Azmi Anfasa ikercasillasr
22. 1102223064 AAA Development (CMD) 081387727480
Rizqi ma
Division
SC Creative Media
dimassbim
23. 1102223167 Dimas Bima Aditya MAS Development (CMD) 081275554718
aaa
Division
SC Creative Media
24. 1106220025 Ahmed Albatsa AMG Development (CMD) 081390831098 stuckin16
Division
SC Creative Media
gakwtggak
25. 1102223153 Reyhan Andhata Pratama RAP Development (CMD) 081256288031
makan
Division
SC Creative Media
aswangga0
26. 1102223027 Aswangga Pandita Sadu WGG Development (CMD) 082337495615
3
Division
SC Human Resource
nathan_ary
27. 1101220356 Nathan Aryasatya Andhika NTR Development (HRD) 087824692740
asatya
Division
SC Human Resource
28. 1106220009 Dega Pradipta Ramadhan DPR Development (HRD) 089529438818 degapr
Division
SC Human Resource
29. 1102223029 Agus Miftah Parid GUS Development (HRD) 082119580837 mifthprd
Division
SC Human Resource
30. 1105220073 Lathifah Husnun TIP Development (HRD) 085846522753 thifahus
Division
SC Human Resource
Muhammad Pachla Tigusti
31. 1104220014 CLA Development (HRD) 081779016013 pachlaa
Agung
Division
SC Human Resource
32. 1101223209 Aulia Ramadhani LLY Development (HRD) 085649100095 lily_elui
Division
SC Division Rules and
33. 1104220143 Shedy Indra Maulana LEX 087784173073 arghh_nju
Discipline Committee (RDC)
Member of Maintenance
kuinginma
84. 101042330098 Chezta Adabi Hidayat CHZ and Logistics Committee 081297503878
ma
(MLC) Division
Member of Maintenance
darmapam
85. 101012330221 Darma Al Gani GAN and Logistics Committee 089513829923
atan
(MLC) Division
Member of Maintenance
erushaandi
86. 101022300072 Ersha Anandita Larasati SHA and Logistics Committee 085891666055
ta77
(MLC) Division
Member of Maintenance
87. 101012300189 Arga Ulya Abdurohman ARG and Logistics Committee 087885281059 argaulyaa
(MLC) Division
In addition to these basic facilities, many modern IDEs also offer additional features such as:
• Integration with Frameworks and Libraries: Makes it easy for developers to import and use
a variety of popular development tools.
• Visualization Tools: Such as graphical user interface (GUI) editors, diagrams, or performance
analysis tools.
• Marketplace or Plugins: Allows developers to customize the IDE by adding extensions or
plugins as per specific needs.
To some extent, modern IDEs can help provide suggestions that speed up writing. When
Algorithm and Programming Practicum Module 2024/2025
1
writing code, IDEs can also point out parts that clearly contain errors or doubts. The Computer
Basics Laboratory will use the Visual Studio Code IDE during the practicum. Here's how to install the
Visual Studio Code IDE.
2) Specify where Visual Studio Code will be installed. By default, it will be installed in the directory
'C:\Users\Admin\AppData\Local\Programs\Microsoft VS Code'. Then click Next.
3) Specify where to place the Visual Studio Code files, then click Next.
5) Make sure all previously selected options are correct, then click Install.
Algorithm and Programming Practicum Module 2024/2025
3
6) Wait until the installation process is complete.
11) By default tdm-gcc will be installed in C:\TDM-GCC-XX and then click Next to continue with
Algorithm and Programming Practicum Module 2024/2025
5
Install without changing any rules.
12) When the installation is complete, it will display the words completed successfully, click Next and
Finish.
13) Once the installation of 'tdm-gcc' is complete, open Visual Studio Code and switch to the
extensions page, and search for C/C++ Extension Pack and click Install.
15) After Code Runner is installed, right-click on the Code Runner extension and click Extension
Settings. Then look for the option as shown in the image below to run Code Runner on the
Visual Studio Code terminal.
16) In using Visual Studio Code, errors are often encountered in outputting a program. This is caused
by Windows security which prohibits running or executing the program file. Windows
automatically reads every folder to the file on the laptop. So there is a way to overcome this,
namely by giving an exception to the folder not to be read by Windows security. Here are the
steps for the folder exception step:
1. Go to Windows Settings
• Click Add an exclusion -> folder (This folder is used as a storage place for the program
to be run)
If there is already an address name for the selected folder, then the folder exception
step has been completed.
3) If a tab like the one above appears, select Yes, I trust the author.
5) After clicking New File, we will be directed to fill in the file name.
File naming rules:
• Avoid using spaces, punctuation, or other special characters. If you want to separate the first
and second words, use “_”. Example: hello_world
• Use the .c extension. Example: hello_world.c
An algorithm is a series of precise, detailed, and limited steps in solving a problem. Precise
means that the steps are always correct to solve the problem. Detailed means that the steps are
detailed and can be executed by a computer. Limited means that at some point the steps must
stop. If the steps "never" stop, it is called looping forever.
As a simple example, you are asked to calculate the perimeter of a rectangle. In this case, you
can specify the output as the perimeter and the input as the length and width. After that, you must
specify how the perimeter of the rectangle is calculated based on the length and width data.
or
Perimeter = 2 x (length + width)
Algorithms are not always expressed in human language as exemplified earlier. Often
algorithms are expressed in the form of pseudocode or flowcharts.
1. Pseudocode
Pseudocodeis a form of algorithm that uses various notations that are intended to simplify
the form of human sentences. For example, a sentence like "Calculate the perimeter of a
rectangle using the formula 2x(length+width)" can be simplified to: perimeter ->
2x(length+width).
Pseudocodeoften oriented to a particular programming language. The following example
shows pseudocode oriented to the Pascal programming language (pseudopascal).
Algorithm (Pseudopascal)
Dictionary :
p, l, k : integer
Algorithm :
output('Length = ')
input(p)
output('Width = ')
input(l)
k -> 2*(p+l) output('Perimeter of Rectangle = ', k
Algorithm and Programming Practicum Module 2024/2025
11
2. Flowchart
Flowchart is a standard for describing a process. Each step in the algorithm is represented by
a symbol and the flow of each step (from one step to another) is represented by a line with an
arrow.
Here are some rules to keep in mind when creating a flowchart:
1. Flowchart is depicted from top to bottom and left to right.
2. The activities described must be carefully defined and these definitions must be
understandable to the reader.
3. When the activity starts and endsmust be clearly defined.
4. Each step of the activity must be described clearly using descriptive verbs, for example
calculating sales tax.
5. Every step of the activities must be in the correct order.
6. The scope and range of the activity being described should be carefully traced. Branches
that intersect the activity being described need not be shown on the same flowchart.
Connector symbols should be used and the branches placed on separate pages or
omitted altogether if the branch is not relevant to the system.
7. Use standard flowchart symbols.
The image above is a simple example of the C programming structure. In the code above
there is a printf function. This function is used to print text to the screen, so if we run it, the
sentence Hello World will appear. In addition, the "\n" sign will cause the cursor to move to the next
line after Hello World is output. Return "return 0" states that the return value of the program is
zero. The value zero is usually used to indicate that the program has successfully carried out its task.
Keep in mind that every statement in the C language must end with a semicolon (;).
Comments are texts inserted into the code to document the program and improve the
readability of the code. Comments will not be executed by the program or will be ignored by the
program. Comments are divided into two types, namely single-line comments, and multi-line
comments. Single-line comments are marked by “//” as in lines 1 and 10 in the example above.
Multi-line comments are marked by “/* … */” as in lines 4 and 5 in the example above. The
difference between the two types above is that single-line comments are only used for one line,
while multi-line comments can be used for more than one line, as long as our comment starts after
the “/*” sign and ends with the “*/” sign or in other words, our comment is between the “/* … */”
signs.
2 #include <stdio.h>
• Main Function
6 int main() {
7 // Displays “Hello World”
8 printf("Hello World! \n");
9 return 0;
10 }// end of main function
The main function is part of every C program. The parentheses after “main” indicate that
“main” is a function. In C, it can consist of one or more functions, one of which is the mandatory
function main(). This function is where the C program starts its execution.
Functions can return a value through the return syntax. The word “int” before “main”
indicates that the “main” function will return a value of type “int” or an integer. “int” is a type of data
type in the C programming language, but will be discussed further in module 2. Return values will
be discussed further in module 5.
The curly braces in the function “{…}” indicate the body or contents of a function. The code
in the body of a function (in this example, on lines 7 and 8) will be executed, otherwise, it will not be
executed.
• printf() function
The printf(“…”) function is a function that will display a string or sentence that is between
double quotes on the output terminal. The printf() function has been defined in the <stdio.h>
header.
On line 7, there is also a “\n” sign, which is an example of an escape character that starts
with “\” or a backslash. Escape characters will not be displayed by the printf() function. Here are
some examples of escape characters:
Escape Character Explanation
\n Newline. Positions the cursor at the beginning of the next line.
\t Tab. Positions the cursor on the next tab.
\\ Backlash. Displays a backslash on the output.
\” Double quote. Displays double quotes in the output.
Examples of input and output from the program above: (input is marked with UNDERLINED text)
Enter a number: 25
The number entered is 25.
6 int var;
A variable is a name that indicates a place in computer memory and contains a value, and
a variable's value can change at any time while the program is executing.
Line 6 is an example of declaring a variable. Every variable in C MUST be declared before it
can be used. In this example, a variable is declared with the name "var" and type "int". Explanations
about variables and data types along with their rules will be explained in module 2, but for now we
just need to know what a variable is.
12 scanf(“%d”, &var);
The scanf() function is a function that will receive input from the user. Just like printf(),
scanf() is also found in the <stdio.h> header. For an explanation of the scanf() function and
its rules will be explained further in module 2, but for now we just need to know what the use of this
function is.
2) After that, the Variable, Watch, Breakpoint, and other tabs will appear. The Variables tab contains
information about the variables we use. Breakpoint itself can be used to stop the program at a
certain point. While Watch allows us to observe the value of the variable while the program is
executing.
3) To add a Breakpoint, move the cursor to the left of the row number, then a red dot will appear,
then click on the red dot.
5) Click the “+” icon or add expression, then type the name of the variable you want to display in
the Expression to watch column.
6) Then when we run the program, the program will automatically stop at the breakpoint we choose
(line 8) and in the watch section we can observe the variable we want to observe, namely "k".
/*The value of a constant must be assigned directly, while a variable does not need
to be assigned directly*/
// Declare a variable.
int long;
int height;
// Multiple variables can also be declared in one line with the same type.
int radius, diameter;
Important things to pay attention to when naming variables and constants include:
i. must start with a letter of the alphabet (A..Z, a..z) or an underscore ( _ );
ii. the next character can be a letter, digit or underscore character ( _ );
iii. the maximum length of an identifier is 32 characters, if it is longer then the first 32 characters
are considered;
iv. may not use spaces;
v. may not use arithmetic operators ( + - / * % );
vi. must not use special characters such as : , ; # @ ( . ) & and $;
vii. C language is case-sensitive, so capital and non-capital letters are distinguished.
Example of input and output from the program above: (input is marked with UNDERLINE text)
• scanf() command
15 scanf(“%d”, &var1);
The scanf() command is a function contained in the <stdio.h> header which functions
to take input from the user. The scanf() command takes two arguments, which in this example
are %d and &var1.
The first argument, %d, is a type of data type format specifier or indicates the type of data
that the user should enter. %d indicates that the type of data entered is an integer. Format specifiers
will be discussed in the next section.
The above code has 1 constant phi with data type int and 2 variables, namely r and area,
each with data type int and float. In the code there is a scanf function which is used to read input
from the user in the form of numbers, either int or float data types. The // symbol is used to mark a
single-line comment. This comment will not be executed by the compiler and is usually used as a
description or note to understand the code on that line.
In addition to the above program, there is another form of using constants using #define
which is used to define a variable (input - output pins etc.) with a new variable name so that in
making our program it is easier to remember the variable name, therefore try to define a variable
using a variable name that reflects its function. The use of #define can be seen in the following
example.
1 #include<stdio.h> INPUT
2 Enter the radius of the
3 // Declare constants circle = 7
4 #define phi 3.14
5 OUTPUT
6 int main() Area of circle = 153.86
7 {
8 // Declare variables
9 int r;
10 float area;
11
12 // Enter the radius
13 printf(“Enter the
radius of the circle =
”);
14 scanf(“%d”, &r);
15
16 // Calculate area
16 area = phi * r * r;
17
18 // Output the area of a
circle
19 printf(“Area of circle
= %.2f \n”, area);
20
21 return 0;
22 }
2.4 Struct
The struct is a data type created by the user. This type is created because there is a
relationship between variables that when combined have the same purpose. To create a
constructed data type, the keyword "struct" is used. One example of a constructed data type is a
student, where students have a name, student ID number, major, and grade.
In the code above, there is a gets() function that plays the same role as scanf(), but they
have differences. If we input a string using scanf(), the string will only be read until a space is found.
For example, "Cristiano Ronaldo", then only Cristiano will be read, while Ronaldo will not be read
because before the word the program has found a space.
In using the gets function, we simply write the variable we want to enter, such as
gets(variable). If the program uses a struct, the gets function is written as gets(variable
struct.variable). In addition, in the code above there is a \t symbol that will add a space that is the
same distance as a tab.
In the application of the data type formation can also be done like the program above.
This is useful for simplifying a program and facilitating the work in compiling a program, so that it
can be more efficient in compiling a program. The data type formation uses the Structure name as
an alias to declare variables containing the data type formation, so you only need to call struct
structureName variableName.
Boolean
operators Example Information
C Algorithm
== = a == b Values true if a is the same as b
< < a<b Values true if the value of a is less than b
<= ≤ a <= b Values true if the value of a is less than / equal to b
> > a>b It has a true value if the value of a is greater than b.
>= ≥ a >= b Value is true if the value of a is greater than / equal to b.
!= ≠ a!=b Values true if the value of a is not the same as b
The following is a table showing the logical operations AND, OR, XOR and NOT on two boolean
values:
a b a and b a or b a xor b
False False False False False
False True False True True
True False False True True
True True True True False
AND operator: && OR operator: ||
OperatorNOT: ! XOR operator : ^
a NOTa
False True
True False
Example:
if (height >= 140) {
printf(“VALID!”);
printf(“Please enter”);
} else {
printf(“INVALID!”):
}
Similar to point a, the program above will display “Login Successful” if the username and
password entered match those in the program line above, namely “Looping” and “Forever).
Further explanation of the above program:
The condition “if (strcmp(user, "Looping") ==0 && strcmp(pass, "Forever") ==0)” states that
if the user name entered is the same as “Looping” AND the pass entered is “Forever”, then the
program will perform the if action, namely “Login Successful” and “Please Continue”. If it does not
match, it will display the else condition.
Flow chart
The program above is an example of the use of the “case of” case. The action to be
performed depends on the value of the variable i. When i is 1, the program will display
the word 'Monday', and so on until the value of i displays the number 7. The 'break'
command is used to stop the action performed in the case so that the action in the next
case is not processed. The 'default' command works if cases 1-7 are not met.
4.1 Repetition
Loops in programming are used to repeat a particular block of code until a desired condition is
met.There are 3 main structures in the loop, namely as follows:
1. Initialization
Initialization is the initial condition of the loop, where a value is given to the counter variable.
2. Condition
Conditions are comparisons that must be met for the loop to run. As long as these conditions
are met, the compiler will continue to loop until the conditions are not met.
3. Update Statement
The update statement is the part for processing the counter variable so that it can fulfill the end
condition of the loop.
The difference between the two will be visible when using the output command as in the example
below:
Increment Program Example Output
#include <stdio.h> i=0
i=0
int main() { Result: i=1
int i=0;//Initialization i=2
Result: i=2
//Checking initial value
printf("i=%d\n",i);
//Post-Increment Example
printf("i=%d\n",i++);
Algorithm and Programming Practicum Module 2024/2025
34
printf("Result: i=%d\n",i);
//Pre-Increment
printf("i=%d\n",++i);
printf("Result: i=%d\n",i);
}
Information:
• The first printf command is used to check the initial value of the variable i.
• In the pre-increment command (++i) produces the value i=2 because the
value is added first and then output. The previous value of i was 1 then
added again to produce the value 2.
Notes:
• If you want to perform a reduction operation on a value or variable, it is called decrement.
example: i– or –i.
Example:
while (i < 3){
printf(“%d ”, i);
i++;
}
In the example above there is an action "i = i + 1" which will change the output of the condition
"i <= 10" to false (when i > 10) so that the loop will stop. This means "i must have a value of <=
10" to be true otherwise false.
2. Do while loop
In the iteration methodThis action will be performed at least once, this is due to the condition
check after the action is performed for the first time. The action will continue to be
performed as long as the condition is true and stops when the condition is false. So, even
though the condition is false, the program will still perform the action once. In this loop, the
number of loops is not yet known for sure.
Notes:
• The i++ statement is identical to i=i+1;
Declaration:
for(initialization; condition; update statement){
// action
// action
// action
}
Notes:
• If you want to count down (eg 10 1) then use for(i=10; i>=1; i--)
• Example program to enter some data using loop
scanf() has a weakness that leaves “\n” (newline) in the input memory, so if there is a
gets() after scanf(), the gets() will not work. The solution is to add getchar() after scanf()
which functions to take “\n” in the input memory so that gets() can work.
Control commands are used in loops to change the result of loop execution from its normal state.
Below are the control commands in loops:
5.2 Functions
Functions are very useful subprograms in programming, especially for developing large and
complex programs. By using functions, we can organize code into smaller, more understandable,
and more manageable parts.
Here are some important terms that are often used in the context of functions:
❖ Local Variable is a variable declared inside a function and can only be used within the scope
of that function. This variable cannot be accessed outside the function.
❖ Global Variable is a variable declared outside all functions, usually at the beginning of the
program. This variable can be accessed and used by all parts of the program, including existing
functions.
❖ Actual Parameter is a value or reference that is given to a function when the function is called.
❖ Formal Parameter is a variable declared inside the function header and is used to receive the
value of the actual parameter when the function is called.
#include <stdio.h>
Global Variable int add(int a, int b);
int x,y; Actual Parameter
void main(){
printf("First Number : "); scanf("%d",&x);
printf("Second Number : "); scanf("%d",&y);
printf("Summation Result = %d",add(x,y));
} Formal Parameter
Output
Example :
Flow chart
6.1 Array
An array is a structured data type that can store lots of data with the same name and occupy
space in memory sequentially and also has the same data type.
An example of array implementation is as follows:
If you want to input 5 data. Without using an array, you have to create 5 different variables
for each data. If using an array, you only need to create 1 variable in the form of an array.
Like variables in general, arrays need to be declared. The difference between regular data types and
arrays is that arrays use square brackets “[...]” after the variable name as an indication of the size of
an array, with the following example:
int number[10];
The example above declares that an array named “number” has a capacity of 10 elements, with the
data type “int”. The value of the array can also be determined in the initialization by:
int number[5] = {1, 2, 3, 4, 5};
The example above declares the array “numbers” with a capacity of 5, with the values: 1, 2, 3, 4, and
5.
Array elements 5 2 3 4 6 7 8 1 12 9
Array index → 0 1 2 3 4 5 6 7 8 9
Array indexes serve as address numbers.
Array elements (contents of each locker) 5 10 7 2 11 Array [5] may contain 5 data,
Array index (locker number) → 0 1 2 3 4
C Input
1 #include <stdio.h>
2
3 int data[100], i, n;
4
5 int main(){
6 printf("Enter number of data: ");
7 scanf("%d", &n);
8 for (i = 0; i < n; i++) {
9 printf("Data Number %d : ",
i+1);
10 scanf("%d", &data[i]);
11 }
12 }
Input
INPUT EXAMPLE
Enter number of data : 5
Data Number 1 : 5
Data Number 2 : 23
Data Number 3 : 4
Data Number 4 : 89
Data Number 5 : 46
struct
{
char name[20], nim[20];
int score;
} student[100];
int i, n;
int main()
{
printf("Number of students: ");
scanf("%d", &n);
for (i = 0; i <= n - 1; i++)
{
printf("Student %d\n", i + 1);
printf("Name\t: ");
fflush(stdin);
gets(student[i].name);
printf("NIM\t: ");
gets(student[i].nim);
printf("Score\t: ");
scanf("%d", &student[i].score);
}
printf("\n");
printf("Student Data\n");
for (i = 0; i <= n - 1; i++)
{
printf("Student %d\n", i + 1);
printf("Name\t: %s\n", student[i].name);
printf("NIM\t: %s\n", student[i].nim);
printf("Score\t: %d\n", student[i].score);
}
return 0;
}
In the example above, the syntax fflush(stdin) is used. This syntax functions to empty
the input buffer. Without using fflush(stdin), the gets() function that is executed is only the
first gets(), while the second gets() function and so on will not be executed by the program.
char word[100];
int length;
int main() {
printf("Enter a word\t : "); gets(word);
length = strlen(word)-1;
printf("Start Word\t : %s\n", word);
printf("Inversion Result : ");
for(length; length >= 0; length--){
printf("%c", word[length]);
}
}
Array of char is an example of using string as an array. The program above is used to reverse
a sentence. It can be seen that the syntax 'strlen()' is used to find out the length of a string.
Here is an illustrative example of an array with two dimensions, where the range 1 -
m is for rows and the range 1 - n is for columns.
1 2 ... n
1 (1,1) (1,2) ... (1,n)
2 (2.1) (2,2) ... (2,n)
... ... ... ... ...
m (m,1) (m,2) ... (M N)
C
#include <stdio.h>
int i, j, m, n;
int mat1[50][50], mat2[50][50], mat3[50][50];
int main(){
printf("Number of Rows\t: ");
scanf("%d", &m);
printf("Number of Columns\t: ");
Algorithm and Programming Practicum Module 2024/2025
51
scanf("%d", &n);
printf("Matrix 1\n");
for (i = 0; i <= m - 1; i++){
for (j = 0; j <= n - 1; j++){
printf("Fill in row %d, column %d = ", i + 1, j + 1);
scanf("%d", &mat1[i][j]);
}
}
printf("Matrix 2\n");
for (i = 0; i <= m - 1; i++){
for (j = 0; j <= n - 1; j++){
printf("Fill in row %d, column %d = ", i + 1, j + 1);
scanf("%d", &mat2[i][j]);
}
}
for (i = 0; i <= m - 1; i++){
for (j = 0; j <= n - 1; j++){
mat3[i][j] = mat1[i][j] + mat2[i][j];
}
}
printf("matrix addition result\n");
for (i = 0; i <= m - 1; i++){
for (j = 0; j <= n - 1; j++){
printf("%d", mat3[i][j]);
printf("\n");
}
}
}
Flow chart
String processing can be done by copying a variable containing a string and storing it in a
new variable to store the copied string, or by combining the two strings into one. In addition, the
process of searching for a character or substring from the main string provided can also be done,
and can also search for the length of a string, along with utilizing custom error code messages
created independently by the user.
For this module, it is recommended to use one of the following two functions to input strings
on the terminal or command prompt, namely: gets() and fgets(). For the procedure for use,
you can see it from various sources on the internet, and try to learn how to use fgets() in order
to minimize the number of warnings caused by it, use gets()because this also affects your
assessment in terms of reducing the risk of many warning messages appearing when running the
program.
The following table will present the functions and macros in the standard library/header file
<string.h> complete with explanation.
#include <string.h>
This module will be more focused on understanding the concept of string processing in C
language using array of characters, until you can learn independently about various string
manipulation tricks with pointer-to characters type. Furthermore, more details will be given about
string processing that can interact directly with the user, namely with various methods that have
been explained briefly in the table above, namely how to copy one string to another, combine two
strings, compare two strings, and search for characters or substrings from a particular string.
In addition, you will also learn about how to manipulate strings with other libraries that are
useful for dealing with error code cases in programming, so that you can better understand how to
solve problems with various errors.
The following will present four (4) general string processing methods in the C language along with
a table containing program code with explanations.
For the string copying process, two functions are provided which are quite easy to use and
manipulate. Use the function strcpy(). If we only want to copy a string from the source to the
destination without paying attention to the maximum character copying capacity, whereas if when
copying a string and we want to ensure the maximum number of characters that can be copied, we
can use the function strncpy() to prevent entire characters being copied to the destination string
(in some cases of course)..
Unlike the process of copying the string above, in the process of merging the source and
destination strings will not overwrite or eliminate each other. Use the strcat() function to combine
two different string variables into one without considering the maximum capacity of combining
characters from one to another, while if we want to ensure the number of characters that can be
combined with other strings, then the strncat() function can be used, for the same reason as in
strncpy() before.
Note that writing one character differently (even though it looks the same visually, but when
checked the value or ASCII code of the character is not the same), will have a big impact on the
output value given, both by strcmp() and strncmp(). Furthermore, in the process of comparing
the two strings using the strncmp() function, if the maximum character to be compared is included,
it will only be checked up to the umpteenth character of the maximum value of the character
comparison.
In simple terms, the function strlen() very useful for counting how many characters there
are in a string type variable, with the note that the measurement systematics does not involve the
null-terminator character '\0' which is at the end of each string, because this character is only a sign
that the string only consists of so many characters, no more or less.
Next, if we want to search for a character in a string, we can use a function strchr(). Simply
include a string as its first parameter and a character (can be typed with single quote notation or
directly as the ASCII code of the character in the form of int or unsigned char) as the second
parameter, with the function's return value being the first character encountered first if found, or
NULL if not found. In addition to searching for the existence of a character in a string, functionality
is also provided in searching for substrings (or in other words, small or large parts of the string we
provide) with the intention of finding similarities using the strstr() function. Only this time the
second parameter of strstr() is the substring in the form of a string (either an array of characters
or a pointer-to characters), with the principle of the output value of the function being the same as
strchr(), but it is not the first character encountered, but rather the match of the first substring
encountered first.
In this fourth method, we will discuss an example of using the function of <string.h>, that
is strerror() which can be useful to train you on how to do error-handling that can be customized
error messages in advance through the programmer to the user, so that we can provide detailed
analysis of the problems experienced along with error codes or messages given directly through the
system. In order to maximize the potential of the function strerror(). Here, we can use the header
file facility from <errno.h> to be able to dive deeper and dig into the various error codes that the
system is capable of giving (and of course will vary from one operating system to another). Note
that the parameters of strerror(), only accepts one parameter, namely an error code in the form
of int errnum, where errnum is a custom error code from the user, or it can be from his/her
intervention <errno.h>.
Sorting in this module is defined as a sorting algorithm. Sorting can be done by ascending (sorting
from the smallest value to the largest value) and descending (sorting from the largest value to the
smallest). There are several methods that can be used to sort data. However, in this practicum, 3
methods will be discussed, namely:
The following is an example of ascending sorting (order from smallest to largest) using the
selection method:
Array A
3 2 1 7 4 3
• Step 1
1 2 3 7 4 3
Find the minimum data in the Array (Index 0-5) then swap it with the data at index 0 then
isolate. It is found that the minimum value in the Array is number 1 (Index 2) so swap it with
number 3 (Index 0) then isolate.
• Step 2
1 2 3 7 4 3
• Step 3
1 2 3 7 4 3
Find the minimum data contained in the Array (Index 2-5) then swap it with the data at the
2nd index then isolate. It is found that the minimum value in the Array (Index 2-5) is the
number 3 (2nd Index), because the number is already in the 2nd Index so it does not swap
places then isolate.
• Step 4
1 2 3 3 4 7
Find the minimum data in the Array (Index 3-5) then swap it with the data in the 3rd index
then isolate. It is found that the minimum value in the Array (Index 3-5) is the number 3 (5th
Index) so swap it with the number 7 (3rd Index) then isolate.
• Step 5
1 2 3 3 4 7
Find the minimum data contained in the Array (Index 4-5) then swap it with the data at the
4th index then isolate. It is found that the minimum value in the Array (Index 4-5) is the
number 4 (4th Index) because the number is already in the 4th Index so it does not swap
places then isolate.
• Step 6
1 2 3 3 4 7
3 2 1 7 4 3
The data at A[1] (second index) has a value of 2 compared to the data on the left A[0], which is
in the gray area. Because 2 < 3, we need to insert the data at index one (2) into the gray area
so that after the insertion, the gray part remains in a relatively sorted state, the method is as
follows:
3 1 7 4 3
2 3 1 7 4 3
c. The first two data are sorted relatively, then insert the third data in the gray section in the same
way as steps a and b. Where the data in A[2] is smaller than the data in A[1] and A[0]. Then
array A will be as below.
1 2 3 7 4 3
1 2 3 7 4 3
1 2 3 3 4 7
Array A
3 2 1 7 4 3
• Step 1
2 3 1 7 4 3
Compare the first data (Index 0), which is 3, with the second data (Index 1), which is 2, because
3 > 2, so a place swap process occurs.
• Step 2
2 1 3 7 4 3
Compare the second data (1st Index) which is 3 with the third data (2nd Index) which is 1,
because 3 > 1 so a place swap process occurs.
• Step 3
2 1 3 7 4 3
Compare the third data (2nd Index) which is 3 with the fourth data (3rd Index) which is 7,
because 3 < 7 so there is no exchange process because what we want is ascending (smallest
to largest order).
• Step 4
Repeat the process until the data is sorted.
2 1 3 4 7 3
1 2 3 4 3 7
1 2 3 4 3 7
1 2 3 4 3 7
1 2 3 3 4 7
One of the most common processes in programming is searching. A search algorithm is the
process of finding the location of a particular element or value in a collection of data. In this module,
we will learn two basic search algorithms, namely sequential search and binary search.
4 21 36 14 62 92 6
For example, if the data we want to search for is 14, then we will compare it one by one with the
data in the array, starting at index 0 to the last index.
4 is not equal to 14
Index
4 21 36 14 62 92 6
4 21 36 14 62 92 6
Index
36 is not equal to 14
2
4 21 36 14 62 92 6
4 21 36 14 62 92 6
Flow chart
In an array of size N, to use binary search, three indexes are needed, namely the low index
(low = 0), the high index (high = N – 1), and the mid index (mid = (low + mid) / 2). The data being
searched will be compared with the array data at the mid index. Consider an array that is sorted in
ascending order:
- If the data A[mid] is greater than the data being searched for, the search area will be
narrowed (the high value becomes mid - 1).
- If the data A[mid] is smaller than the data being searched for, the search area will be
narrowed (the low value becomes mid + 1).
For example, if the data we want to search for is 10, then here is the process.
Low Mid High
0 5 11 21 > 10
4 7 8 10 14 21 22 36 62 77 81 91
B[0] B[1] B[2] B[3] B[4] B[5] B[6] B[7] B[8] B[9] B[10] B[11]
4 7 8 10 14 21 22 36 62 77 81 91
B[0] B[1] B[2] B[3] B[4] B[5] B[6] B[7] B[8] B[9] B[10] B[11]
4 7 8 10 14 21 22 36 62 77 81 91
B[0] B[1] B[2] B[3] B[4] B[5] B[6] B[7] B[8] B[9] B[10] B[11]
The strength variable is at address abcd and blood is at abce. Memory addresses can be
written in hexadecimal (example: abcd), decimal (example: 43981), or binary (example:
1010101111001101). The memory address of a variable is chosen randomly.
Pointer is a special variable that stores a memory address, not a data value directly. It can
allow direct data manipulation at a specific memory address, important for dynamic memory
allocation and management of complex data structures, but its use requires caution because it can
cause program crashes or difficult-to-track bugs if not managed properly.
In C language, to get the memory address of a variable, the ampersand operator (&) is used.
Then this address can be stored into a pointer type variable. Declaring a pointer variable is done by
adding an asterisk (*) in front of the variable name (spaces have no effect), following the general
form:
data_type *pointer_name;
example:
int *ptr_daskom;
float *ptr_daskom;
char* ptr_daskom;
3. Managing arrays. Pointers are often used to manage arrays. Arrays in C are actually pointers
to consecutive blocks of memory.
Example:
1 int arr[] = {1, 2, 3, 4, 5};
2 int *ptr = arr;
3 for (int i = 0; i < 5; i++) {
4 printf("%d ", *(ptr + i));
5 }
4. Dynamic memory allocation. Pointers are used in conjunction with functions such as malloc,
calloc, and free to manage memory dynamically.
Example:
1 int *ptr;
2 ptr = (int*)malloc(sizeof(int) * 5); // Allocate memory
for 5 integers
3 if (ptr == NULL) {
4 printf("Memory allocation failed");
5 return 1;
6 }
7 for (int i = 0; i < 5; i++) {
8 ptr[i] = i + 1;
9 }
10 free(ptr); // Returns the allocated memory
Using pointers in C offers some significant advantages, especially in terms of efficiency and flexibility.
Here are some of the main advantages:
1. Memory efficiency. Pointers allow for more efficient memory management. By using pointers,
we can allocate and free memory as needed by the program, avoiding memory waste.
2. Direct access and modification. With pointers, we can access and modify data directly at a
specific memory location without requiring a copy of the data. This can be a huge time and
resource saver in applications that process large amounts of data.
3. Managing dynamic data structures. Pointers are very useful in managing dynamic data
structures such as linked lists, trees, and graphs, where elements can be dynamically
connected at runtime.
4. Managing arrays and strings. Pointers allow us to work with arrays and strings in a more
flexible way. We can easily access and manipulate array elements or string characters
through pointers.
5. Interaction with hardware. Pointers allow direct interaction with hardware through memory
addressing. This is very useful in low-level system programming, such as in embedded
systems and device drivers.
6. Supports dynamic memory allocation. With pointers, we can use dynamic memory allocation
functions such as malloc, calloc, and free to manage memory dynamically. This allows the
creation of flexible data structures that can change size at runtime.
Difference between Pointers and Regular Variables
1. Common Variables
a. Contains data/values.
b. Common operators include arithmetic operators, bitwise operators, etc.
c. Static in nature.
d. Declaration : “int a;”
2. Pointers
a. Contains the memory address of a particular variable.
b. Requires special operators such as dereference and address-of operators.
c. Dynamic in nature.
d. Declaration: “int *a;”.
1 #include <stdio.h>
2 int main() {
4 int *ptr = score;// ptr points to the address of the first element of arr
5 // array address
7
8 // array values can be accessed with pointers
11
17 }
18 return 0;
19 }
Example:
Struct Example:
struct student {
char name[50];
int nim;
float value;
} student_data;
Example:
struct student {
char name[50];
int nim;
float value;
} data_mahasiswa[30]; //example of using array in struct
1. malloc
• malloc is short for "memory allocation".
• The malloc function is used to allocate blocks of memory from the heap (dynamic memory)
during program runtime.
• The general syntax is void *malloc(size_t size);.
• malloc returns a pointer to the allocated memory block, or NULL if the allocation fails.
• Usage example: ptr = (int *) malloc(10 * sizeof(int)); will allocate memory for 10 integers.
2. free
• free is used to free a block of memory that has been previously allocated using malloc, calloc,
or realloc.
• The general syntax is void free(void *ptr);.
• ptr is a pointer to the block of memory to be freed.
• Freeing up unused memory prevents memory leaks.
• Usage example: free(ptr); will free the memory allocated to ptr.
FILE *file_pointer_identifier;
FILE *fp
For example, we will declare a pointer with the name fp to point to the FILE structure, then the
writing syntax is as follows:
Operations on files involve three main stages.
1. Open/activate file
2. Processing files
3. Closing a file
FILE *fopen (const char * restrict filename, const char * restrict mode);
Description :
❖ filename, is the name of the file (string) to be opened.
❖ mode, in the form of the type of operation (string) that will be performed on the file.
❖ Henceforth, the basic form in this module is contained in the stdio.h file.
❖ The function will return a pointer pointing to an object (FILE) to control the flow of data of a file.
If the file opening operation fails, fopen will return a NULL pointer (a null pointer constant
defined by the implementation of a platform).
The following are the modes of fopen in the C language:
Mode Meaning
“r” Opening a file for reading. If the file does not exist, the file will fail to open, but if
the file exists, the file can be read with the initial file position indicator positioned
at the beginning of the file.
“r+” Same as "r", but can also be used for the writing process.
“w” Opening a file for writing. If the file does not exist, the file will be created. If the
file already exists, all contents of the file will be deleted without any prior warning.
Finally, if the file is successfully opened, the file can be written with the initial file
position indicator.
positioned at the beginning of the file.
“w+” Same as "w", but can also be used for the reading process
“a” Opening a file for appending. If the file does not exist, the file will be created. If the
file exists, the process of writing data to the file will be written at the end of a file,
even if there is an intervention of the file positioning function (discussed later in this
module). Finally, if the file is successfully opened, the initial file position indicator will
be positioned based on the implementation of a platform, whether at the beginning
or at the end of the file.
“a+” Same as "a", but can also be used for the reading process.
fp = fopen(“TES.TXT”, “w”);
Notes:
❖ If the mode argument contains a symbol'+' in it, then it is called update mode. Input process
(reading from file) and output (writing to file) can be executed on the current flow of a file in
question.
• TEXT FILE
1. Writing and Reading String Data in Text Files
To write string data to a file, remember that the printf function is usually used to write to the
screen, while the fprintf function can be used to write to a file. Next, to read string data to a file,
there is a function called fgets. Here is its basic form.
char nama[10];
int main(){
FILE *f_teks;
f_teks =
fopen("akun_user.txt", "w");
gets(nama);
fprintf(f_teks,"%s\n", nama);
fclose (f_teks);
return 0;
}
char nama[10];
int main(){
FILE *f_teks;
f_teks = fopen("akun_user.txt",
"r");
while(fgets(nama,sizeof(nama),
f_teks)!=NULL)
printf("%s", nama);
fclose (f_teks);
return 0;
}
The fgets function takes a character from a file with the type unsigned char (has a range of
0 – 255 values in ASCII values) which is then converted to a positive int value. The function returns
a character from the file pointed to by the stream. If a reading error occurs, it will return EOF.
Reading String Data from Text File Using Flow chart
fgetc
#include <stdio.h>
int main() {
FILE *f_teks;
int ch;
f_teks = fopen("akun_user.txt", "r");
fclose(f_teks);
return 0;
}
EOF is a negative constant int defined by the implementation of a platform, this value is
usually returned by some functions such as fgetc to indicate the end of a file, in other words, no
data can be read from that character. Therefore, to read correctly using fgetc, do not declare a
reserved variable to store the character as char, but declare it with int.
char nama[10];
int main(){
FILE *f_teks;
f_teks =
fopen("akun_user.txt", "a");
gets(nama);
fprintf(f_teks, "%s\n",
nama);
fclose (f_teks);
return 0;
}
• BINARY FILE
1. Writing and Reading Data on Binary Files
There are two functions for writing or reading data in the form of memory blocks (consisting
of bytes),for example to write any data type like float or struct. Both functions are called fread and
fwrite. Here is the basic form.
size_t fread(void * restrict ptr, size_t size, size_t nmemb, FILE * restrict stream);
size_t fwrite(const void * restrict ptr, size_t size, size_t nmemb, FILE * restrict stream);
Description :
❖ ptr is a pointer that points to a memory area that will be used as temporary data storage
for reading from a file (for fread) or for writing data to a file (for fwrite).
int main(){
FILE *f_biner;
int n, i;
struct {
char nama[10], nim[10];
int nilai;
} data;
Notes :
In this example, a file withThe name “data_mhs” will have the extension “.dat”, please note that
any extension (including .txt) can be used whether it is a text or binary file.
Reading Data from Binary Files
#include <stdio.h>
int main(){
FILE *f_biner;
struct {
char nama[10], nim[10];
int nilai;
} data;
f_biner = fopen("data_mhs.dat", "rb");
while(fread(&data, sizeof(data), 1, f_biner)==1){
printf("Nama : %s\n", data.nama);
printf("NIM : %s\n", data.nim);
printf("Nilai : %d\n", data.nilai);
}
fclose(f_biner);
return 0;
}
struct {
char nama[10], nim[10];
int nilai;
}data;
Description :
❖ If the operation fails, it will return a non-zero value defined by a platform's implementation.
❖ stream is a file pointer that points to FILE.
❖ offset is the byte adjustment value against the whence reference.
❖ whence is a file position indicator reference.
❖ Remember, after a successful fseek call, the next operation in the data stream
update can be input (reading from a file) or output (writing to a file)
It should be noted that the offset argument can also accept negative values. Extra, the rewind function
Description
❖ The rewind function changes the file position indicator tothe data stream pointed to becomes
the beginning of the file. This is the same as (void)fseek(stream, 0L, SEEK_SET) except that the
error indicator on the data stream is also cleared.
❖ The rewind function does not return a value.
int main(){
FILE *f_biner;
int no_struct;
long int offset_byte;
struct {
char nama[10], nim[10];
int nilai;
}data;
Flow chart
Assume that the file is to be opened in “rb” mode, the initial file position indicator is positioned at
the beginning of the file. If the third data is to be read, fseek(fp, 2 * sizeof(DATA), SEEK_SET) can be
called. fseek will position just before the third data.
7 8 9 10 8
fread
process
Thus, the fread function will read the third data correctly.
C language also provides functions to delete and rename a file, respectively with the
names remove and rename. Here is the basic form:
The remove function causes the file with the string name pointed to by filename to no longer
be accessible by the file with that name. In other words, the file will be gone.
The rename function causes the file with the string name pointed to by old to be recognized
as the name given by the string pointed to by new. The remove and rename functions return an
integer of zero if the operation succeeds and something other than that defined by the platform
implementation if it fails.
Deleting Data in Binary Files
#include <stdio.h>
#include <string.h>
int main(){
FILE *f_biner;
FILE *f_biner2;
Algorithm and Programming Practicum Module 2024/2025
104
char hapus[50];
struct {
char nama[10], nim[10];
int nilai;
}data;
f_biner = fopen("data_mhs.dat", "rb");
f_biner2 = fopen("data_mhs2.dat", "wb");
printf("Silahkan masukkan nama mhs yang akan dihapus: "); gets(hapus);
while (fread(&data,sizeof (data),1, f_biner)==1){
if (strcmp(data.nama, hapus)!=0){
fwrite(&data, sizeof(data), 1, f_biner2);
}
}
fclose(f_biner);
fclose(f_biner2);
remove("data_mhs.dat");
rename("data_mhs2.dat","data_mhs.dat");
return 0;
}
Flow chart
int main()
{
FILE *f_biner;
FILE *f_biner2;
int poin_tambahan = 1, poin_baru = 0;
char user_sekarang[10];
struct
{
char nama[10], nim[10];
int nilai, poin;
} data, temp;
Description :
❖ stream is a file pointer that points to a FILE.
❖ If the fclose function succeeds, it will remove the file data stream pointed to by the stream and
close the file in question. Buffer data for writing processes that have not been written in a data
stream will be written first, but buffer data for reading processes that have not been read will be
discarded.
❖ The fclose function returns zero if the data stream was successfully closed, or EOF if there was a
eerror detected.
Description :
❖ stream is a file pointer that points to a FILE.
❖ Buffer data for the writing process that has not yet been written into a data stream will be written
first.
❖ If the last operation was not input (reading from a file), the fflush function will cause the buffer
data for the write process that has not been written in a data stream to be immediately written
to the file. Otherwise, the behavior of this function is undefined.
❖ The fflush function will set an error indicator for the data stream and return EOF if a write error
occurs. Otherwise it will return zero.
Description :
❖ stream is a file pointer that points to a FILE.
❖ fpos_t is a data type that can store the information needed to uniquely determine each position
within a file.
❖ fgetpos will store the file position indicator in the object pointed to by pos and fsetpos will
change the file position indicator based on the value of the object pointed to by pos.
❖ Both functions will return the integer zero if the operation succeeds and something else defined
by the platform implementation if it fails.
Objective
A report is a form of document or presentation that contains facts about a situation or activity.
The facts presented are related to the responsibility given to the person concerned. This fact contains
a statement or information obtained from observations or experienced by the person who is given
responsibility. In making a report, a basic technical understanding is required in using document-
making applications such as MS Office. Here are some basic techniques that need to be understood in
making a report.
1. Margin
Marginis the distance between the typing edge and the edge of the
paper page. The margins commonly used in making reports are (4-
3-3-3) cm in the order (Left – Right-Top-Bottom).
3. Style Modification
Style Modificationuseful for modifying the writing format of chapter titles, sub-chapters,
captions, and writing in paragraphs. The Modified Styles are Normal, Heading 1, Heading 2, and Caption.
Change the font formatting to Times New Roman, Font Size 12, Font Color Black, OK when finished (For
Normal Text formatting styles).
4. Header Styles
When giving chapter and sub-chapter titles, use Style Heading 1 and Style Heading 2.
Use :
click on the text thatwill be formatted, then click Heading 1 or Heading 2. After the text changes, the
Navigation Panel will appear (can be seen in the view menu) which will show the section that uses
Heading 1 or Heading 2.
5. Caption
Captions are useful as descriptions or explanations that accompany illustrations in the
form of images or tables. To use captions, select the Reference menu Insert Caption New
Label
→ Write 'Picture'.
Algorithm and Programming Practicum Module 2024/2025
111
To insert Numbering in Caption. Reference Caption Numbering Format (1,2,3) check Include
chapter number Chapter starts with style Heading 1 Use Period Separator.
Then use it on the image. Right click on the image Insert Caption Select Image
Below selected items→Ok then give the image a title. For the table list, Right click on the table
→Insert Caption→ Select Table if there is already a table label Position Above selected item.
6. Page Numbering
To number the pages, click on the footer (bottom of the page) of Chapter 1. Select the Insert
menu Page Number Format Page Number Number Format start at 1. For pages before
Chapter 1 (preface, table of contents, list of figures), use the Roman numeral format).
2. To display the List of Figures and List of Tables, select the Reference menu Table of
Contents Custom table of Contents Ok.
• Kadir, A., 2012. Algorithms & Programming Using C & C++. Yogyakarta:
Andi Offset Publisher.
• Prakash, 2019. What are the differences between a pointer variable and a
reference variable in C++?. [Online] Available at:
https://stackoverflow.com/questions/57483/what-are-the-differences-
between-a-pointer-variable-and-a-reference-variable-in
• Schildt, H., 2003. C++: The Complete Reference, Fourth Edition. Osborne:
McGraw-Hill