0% found this document useful (0 votes)
18 views

Basic Computer Lab Module 2024/2025, Algorithms and Programming English Edition

The document is the Algorithm and Programming Practicum Module for the academic year 2024/2025, detailing the introduction, writing team, implementation rules, and laboratory guidelines. It outlines the vision, mission, and objectives of the Faculty of Electrical Engineering at Telkom University, along with specific requirements and rules for students and laboratory assistants participating in practical activities. The document also includes a letter of statement and revision, emphasizing the importance of adherence to safety protocols and academic standards.

Uploaded by

ATC Daskom
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Basic Computer Lab Module 2024/2025, Algorithms and Programming English Edition

The document is the Algorithm and Programming Practicum Module for the academic year 2024/2025, detailing the introduction, writing team, implementation rules, and laboratory guidelines. It outlines the vision, mission, and objectives of the Faculty of Electrical Engineering at Telkom University, along with specific requirements and rules for students and laboratory assistants participating in practical activities. The document also includes a letter of statement and revision, emphasizing the importance of adherence to safety protocols and academic standards.

Uploaded by

ATC Daskom
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 140

INTRODUCTION

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.

Bandung, January 14 2025

Compiler team

Algorithm and Programming Practical Module 2024/2025


i
ALGORITHM AND PROGRAMMING PRACTICUM MODULE WRITING TEAM

Head of Laboratory : Dr. Rahmat Awaludin Salam, S.Si., M.Si.

Person In Charge : Teguh Patriananda 1102223051

Team Leader : Garry Nelson 1102223258

Deputy Team Leader : Dennytan Raharjo 1104223013

Member :

• Ahmed Albatsa 1106220025

• Alika Widuri Kartika 1101223078

• Aliyus Hedri 1102223047

• Aswangga Priest Sadu 1102223027

• Darla Gempita From Purba 1105223068

• Farhan Oktavian 1104223057

• Immanuel Eben Haezer Joseph Aletheia 101022300172

• Justin Fairman Tan 1102223024

• Lathifah Husnun 1105220073

• Muhammad Hafiz 101022300004

• Natasha Fedora Barus 1101223205

• Ni Kadek Cindy Sriastiti 1102223133

• Riza Aria Komara 1105220065

Algorithm and Programming Practical Module 2024/2025


ii
LETTER OF STATEMENT

The undersigned below:

Name : Dr. Rahmat Awaludin Salam, S.Si., M.Si.

NIP : 14890058

Position : Head of Basic Computing Laboratory

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.

Bandung, January 14, 2025

Head of Basic Computing Assistant Coordinator of


Laboratory Basic Computing Laboratory

Dr. Rahmat Awaludin Salam, S.Si., M.Si. Teguh Patriananda


NIP 14890058 NIM 1102223051

Algorithm and Programming Practical Module 2024/2025


iii
BASIC COMPUTING LABORATORY
School of Electrical Engineering – Telkom University
TULT Building 10th floor, Room 10.04
Jl. Telekomunikasi No.1, Terusan Buah Batu, Bandung 40257

LETTER OF REVISION

The undersigned below :


Name : Dr. Rahmat Awaludin Salam, S.Si., M.Si.
NIP : 14890058
Position : Head of Basic Computing Laboratory
Hereby declares that the module for Algorithm and Programming Practicum for
the Telecommunication, Biomedical, and Electrical Energy Engineering study programs has
been revised with details as stated below:

No Module Revision Description Last Revision Date


1 Module 7 Changes in the structure of the material
to sorting
2 Module 8 Changes in the structure of the material
to searching
3 Module 9 Changes in the structure of the material
to pointers
January 14, 2025
4 Module 10 Changes in the structure of the material
to input/output files
3 Module 1-10 Punctuation errors correction,
effective sentences, and typos. Provide
line numbering on some coding to
improve code readability.

Bandung, January 14, 2024

Head of Affairs Assistant Coordinator


Laboratory and Studio, Basic Computing Laboratory,

Dr. Rahmat Awaludin Greetings Teguh Patriananda


NIP 14890058 NIM 1102223051

Algorithm and Programming Practical Module 2024/2025


iv
VISION, MISSION AND OBJECTIVES OF
THE FACULTY OF ELECTRICAL ENGINEERING

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.

Algorithm and Programming Practical Module 2024/2025


v
IMPLEMENTATION OF PRACTICUM ACTIVITIES
EVEN SEMESTER OF ACADEMIC YEAR 2024/2025
FACULTY OF ELECTRICAL ENGINEERING - TELKOM UNIVERSITY
Number: 002/AKD7/TE-WD1/2025
Following up on Letter Number: 358/AKD6/AKD-BAA/2022 concerning the
Implementation of the Lecture Model. The following are the Implementation Rules for
Even Semester Practical Activities for the 2024/2025 Academic Year.
A. Requirements for Participating in Practicum
The requirements for students taking part in the practicum consist of:
1. Students can take part in practicums if they take the practicum course credits and
have or are taking the related course credits.
2. Students who continue to participate in practicum without fulfilling the
requirements of point 1, the practicum score is not valid and cannot be saved.
3. For students who do not pass a particular practical course, they are not required
to take all the practical courses, students can repeat only the practical courses that
they failed.

B. Rules for Implementing Practical Work for Laboratory Assistants


Every laboratory assistant who carries out practical work is required to comply with the
following rules:
1. Laboratory assistants are required to wear the official Telkom University uniform
and bring a valid Student ID Card (KTM).
2. All laboratory assistants with long hair are required to tie their hair back.
3. Laboratory assistants are prohibited from eating and drinking in the room during
the practicum.
4. Laboratory assistants who do not carry out practical assistance according to the
specified schedule for any reason are required to report to the OA Line seelabs.

C. Rules for Implementing Practical Work for Interns


Every practitioner who takes part in the practicum must comply with the following rules:
1. All interns MUST wear the official Telkom University uniform.
2. For safety during the practicum, hair must be neat and practicum participants with
long hair must tie their hair up.
3. The practicum was carried out for 2.5 hours according to the predetermined
schedule.

Algorithm and Programming Practical Module 2024/2025


vi
4. Practitioners must be present 10 minutes before the practicum begins.
5. If the practicum is more than 20 minutes late, the practicum will NOT be allowed
to participate in the practicum activities in the module being implemented.
6. Practitioners can carry out practicums after receiving instructions from the
Practicum Assistant.
7. During the practicum, students are prohibited from:
• Eating, drinking and smoking
• Making noise in the room
• Changing software or hardware configuration
• Leaving the room without the permission of the Practical Assistant
• Using a smartphone without the permission of the Practical Assistant
• Any inappropriate actions taken during the practicum
8. Implementing "special rules" for the flow of practical activities in accordance with
the procedures established by each laboratory.
9. Practitioners who do not practice due to illness, incidents or accidents, religious
services or campus activities that have been permitted by the Central Student
Affairs Division (BK) must report to the OA line seelabs a maximum of three days
after the absence, or three days beforehand.
10. If the practitioner violates rules 1 to 9 above, the practitioner will be subject to
sanctions in accordance with applicable regulations.

Practical Assessment System


1. One practical course at the Faculty of Electrical Engineering consists of 12 practical
modules with the assessment percentage according to the number of modules for
each practical course given.
2. Specifically, the practical assessment system for students taking practical courses
at the Faculty of Electrical Engineering follows the following rules:
a. First Condition
• Practical courses consist of:
a. 1 practical course, totaling 12 practical modules
b. 2 practical subjects, each consisting of 6 practical modules
c. 3 practical subjects, 4 practical modules each
• Students are given tolerance for not attending the practicum, only 1 (one)
meeting for each practicum subject.
• If the absence exceeds the points specified above, the grade for the
practical course will be E.

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.

Algorithm and Programming Practical Module 2024/2025


viii
RULES FOR FOLLOW-UP PRACTICUM
EVEN SEMESTER ACADEMIC YEAR 2024/2025
FACULTY OF ELECTRICAL ENGINEERING - TELKOM UNIVERSITY
Number: 002/AKD7/TE-WD1/2024

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.

Algorithm and Programming Practical Module 2024/2025


ix
2. Academic Dispensation
Interns are required to attach a copy of the proof of dispensation approval from i-
Gracias which has been approved by the Student Affairs Body.

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.

C. The flow of applications for follow-up practicums is as follows:


a. Practitioners submit follow-up practicums online to the OA Line seelabs.
b. The laboratory assistant checks the reasons for submitting the follow-up practicum.
c. The laboratory assistant determines whether the application for follow-up practical
work is approved or rejected.
d. Only students who have been approved by the laboratory assistant are permitted to
take part in follow-up practicums.
e. The laboratory assistant records the follow-up practicum data.
f. The announcement of the list of practicum participants who will take part in the follow-
up practicum will be informed via the OA Line seelabs and FTE Practicum Info on
Telegram.
g. The relevant laboratory assistant determines and informs the schedule for follow-up
practicums.
h. Implementation of follow-up practicums.

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.

Algorithm and Programming Practical Module 2024/2025


x
LABORATORY RULES

Rules that apply in the laboratory:


• It is prohibited to take or take out tools and materials from the laboratory without
the permission of the FTE laboratory assistant.
• Unauthorized persons are prohibited from entering the laboratory to prevent
unwanted incidents.
• Use tools and materials according to the practical instructions provided.
• Do not experiment before knowing information about the tools, chemicals and
how to use them.
• Ask questions if you feel unsure or do not understand while doing the experiment.
• Recognize all types of work safety equipment and their location to facilitate
assistance in the event of a work accident.
• Must know how to use emergency equipment such as fire extinguishers, hydrants,
and other work safety equipment.
• If damage or accident occurs, it is best to immediately report it to the laboratory
staff and FTE laboratory assistant.
• Be careful when working with strongly acidic materials, corrosive reagents, volatile
and flammable reagents.
• Every laboratory assistant must know the location and how to provide first aid
(P3K).
• Throw away rubbish in the rubbish bins provided.
• Try not to be alone in the laboratory so that if an accident occurs you can get help
immediately.
• Don't play around in the laboratory.
• Conduct periodic work safety training.
• Smoking, eating and drinking are prohibited in the laboratory.

Algorithm and Programming Practical Module 2024/2025


xi
LAB LOCATION PLAN

Algorithm and Programming Practical Module 2024/2025


xii
GENERAL GUIDELINES FOR SAFETY AND USE OF LABORATORY
EQUIPMENT

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.

5. Position of table and chairs


Arrange the table and chair so that the sitting position in front of the monitor is more
comfortable and can reach the keyboard and mouse easily. In addition to being
positioned, computer hardware must be well maintained because these devices use
electricity.

6. CPU box position


A CPU box placed on the floor and not equipped with a ground can conduct electricity
when we touch it without shoes. To avoid short circuits, the CPU box should be placed in
a safe place, such as on a table. The CPU box can be grounded by connecting it to the
ground or wall using a piece of copper wire. Because the CPU requires a large amount of
electricity, we must keep it away from liquids and animals or insects to avoid short circuits.

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.

B. Electrical Short Circuit


Pay attention to places where there are power sources and learn how to turn them on
and off. If you see any damage that could potentially cause
danger, report to the assistant on duty.
• Avoid areas or objects that have the potential to cause accidental electrical hazards
(electric shocks), for example, exposed electrical cables, etc.
Algorithm and Programming Practical Module 2024/2025
xiv
• Do not do anything that could cause electrical hazards to yourself or others.
• Dry any body parts that are wet due to, for example, sweat or remaining ablution
water.
• Always be aware of electrical hazards in every practical activity.

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

Main Causes of Fire


The main causes of fires include:
1. Improper heating, namely when flammable substances are heated incorrectly, not
being careful when using an oil bath, and not checking the oil temperature
regularly.
2. The spread of flammable vapors and gases, for example not carrying out proper
cooling during distillation, there is a substance leak, the reaction needs to be
carried out in an acid room/special room, pouring a large amount of flammable
substances, carelessness/spilling of volatile liquids, or poor room ventilation.
3. Persons who are less aware/careless, for example smoking, throwing away
matches, and so on.

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

Algorithm and Programming Practical Module 2024/2025


xv
• Self-Control: Stay calm and don't panic. Panic can make the situation even
harder to control.
2. Tell Everyone
• Warning: Immediately notify everyone in the laboratory of the fire.
• Fire Alarm: Activate the fire alarm if available.
3. Turn Off Power Source
• Electricity: If possible, immediately turn off the main power source to prevent
further fires from electrical short circuits.
4. Use a Fire Extinguisher
• Type of Extinguisher: Use an appropriate fire extinguisher. For electronic fires,
use a type C fire extinguisher specifically designed for electrical devices.
• How to use: Use the fire extinguisher with the PASS method (Pull the pin, Aim
at the base of the fire, Squeeze the handle, Sweep side to side).
5. Evacuation
• Evacuation Route: Follow the designated evacuation route. Do not use the
elevator, use the emergency stairs.
• Check the Door: Before opening the door, check the temperature with the back
of your hand. If it's hot, find another route.
• Stay Low: If the smoke is thick, crawl on the floor to avoid inhaling smoke.
6. Close the door
Fire Isolation: If possible, close the door behind you to slow the spread of fire and
smoke.
7. Call for Help
• Emergency Numbers: Once in a safe place, immediately call the emergency
number to report the fire.
• Information: Provide clear information about the location of the fire and the
current situation.
8. Don't Go Back Inside
• Safety: Do not return to a burning laboratory until authorities say it is safe to
return.

Algorithm and Programming Practical Module 2024/2025


xvi
LIST OF CONTENTS

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

Algorithm and Programming Practical Module 2024/2025


xviii
DASKOM LABORATORY PRACTICUM ASSISTANT 2024/2025

Assistant
No. NIM Name Position Phone Number Line ID
Code
patrianand
1. 1102223051 Teguh Patriananda TGH Assistant coordinator 087885538877
ateguh

2. 1102223258 Garry Nelson SOH Vice Assistant Coordinator 081261469886 gn2004

natashafba
3. 1101223205 Natasha Fedora Barus NFB Admin I 081232644668
rus

4. 1104223146 Dhea Aisyah Putri DEY Admin II 081250770473 dheaaisyyy

5. 1101223028 Indi Viska Rahmasari VIS Practicum Coordinator I 085802253573 indiviska

6. 1104223013 Dennytan Raharjo TAN Practicum Coordinator II 081395882733 dentan77

Vincentius Artyanta artya121212


7. 1102223079 TNT Responsible for Hardware 082322512553
Maheswara Purba 121212121

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

Algorithm and Programming Practical Module 2024/2025


xix
and Task Committee (ATC)

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)

Algorithm and Programming Practical Module 2024/2025


xx
SC Division Rules and
34. 1102223037 Athirah Muthiah Marzuqah THI 082292062883 athirahmth
Discipline Committee (RDC)
SC Division Rules and
35. 1101220021 Muhammad Afwan ONE 081297285194 ice17845
Discipline Committee (RDC)
Rasyad Rifatan Rahman SC Division Rules and rasyadpatia
36. 1102224221 RAD 082255112501
Dingang Patianom Discipline Committee (RDC) nom
SC Division Rules and
37. 1102223047 Aliyus Hedri ALY 082388488916 alyhdr12
Discipline Committee (RDC)
SC Division Rules and
38. 1101224341 Nahda Nabila BIL 085271950028 pnn12
Discipline Committee (RDC)
SC Division Maintenance
hisyamaqie
39. 1102223230 Hisyam Aqiel Sadzilli OIL and Logistics Committee 0895389942605
l41
(MLC)
SC Division Maintenance
Muhammad Nabil Arifiandi nabil15030
40. 1104220154 NST and Logistics Committee 081212115707
Tambunan 4
(MLC)
SC Division Maintenance
41. 1102223269 Danur Herlambang DNR and Logistics Committee 081395782437 danurh222
(MLC)
Coordinator of the
Immanuel Eben Haezer
42. 101022300172 NUE Assignment and Task 085829290950 eintswx
Joseph Aletheia
Committee (ATC) Division
Member of the Assignment
Rafhan Mazaya 03_fhanyu
43. 101012300238 RAF and Task Committee (ATC) 082124795663
Fathurrahman h
Division
Member of the Assignment
Sasqia Gessangie Yohanshah gurame_ba
44. 101012300058 SSS and Task Committee (ATC) 081297703045
Puteri kar
Division
Member of the Assignment
stevannie3
45. 101012340343 Stevannie Pratama SNI and Task Committee (ATC) 085269958753
0
Division
Member of the Assignment
mhafizkusu
46. 101022300004 Muhammad Hafiz MHZ and Task Committee (ATC) 081389137125
ma3
Division
Member of the Assignment
47. 101012300089 Dariele Zebada Sanuwu Gea DAZ and Task Committee (ATC) 082298152826 dariele_gea
Division
Member of the Assignment
gunaawan_
48. 101042330035 Umar Zaki Gunawan UZY and Task Committee (ATC) 085710108151
727
Division
Member of the Assignment
Muhammad Zaenal Abidin zaenal1102
49. 101012300153 ZEN and Task Committee (ATC) 082231639644
Abdurrahman 06
Division

Algorithm and Programming Practical Module 2024/2025


xxi
Coordinator of the Creative
anggiangel
50. 101012300209 Angelica Cecillia ACC Media Development (CMD) 087778173739
icacecilia
Division
Member of the Creative
51. 101042330010 Bunga Nirmala Ramadhani FLO Media Development (CMD) 082320696520 mobbue
Division
Member of the Creative
52. 101022300008 Ahmad Rivaldi Putra VAL Media Development (CMD) 081213538479 ahmdrivldy
Division
Member of the Creative
53. 101052330040 Sakti Risla Syah Putra TRA Media Development (CMD) 0895630020472 putraaxy_
Division
Member of the Creative
54. 101042300014 Radif Putra Permana RAR Media Development (CMD) 0895333431355 radif2503
Division
Member of the Creative
miftah.faqi
55. 101022330177 Muhammad Miftah Faqih MIT Media Development (CMD) 081224466880
h
Division
Member of the Creative
mr_freedw
56. 101022300062 Wijdan Insania Kuncoro DAN Media Development (CMD) 082351996168
hite
Division
Coordinator of the Rules
57. 101012300169 Yattaqi Muazirul Mulki UKI and Discipline Committee 081220331931 muazirul17
(RDC) Division
Member of the Rules and
58. 101012330200 Sayyid Faqih AKI Discipline Committee (RDC) 082210413840 1akii
Division
Member of the Rules and
59. 101012300217 Naila Bening Nurani NAI Discipline Committee (RDC) 08988508667 enaienai
Division
Member of the Rules and
60. 101022330038 Rega Arzula Akbar ARZ Discipline Committee (RDC) 082126565892 arzula233
Division
Member of the Rules and
61. 101012330082 Reza Naufal Akbar RZE Discipline Committee (RDC) 087825931871 rezaxdxp
Division
Member of the Rules and
62. 101042300073 Roudhotul Jannah RDJ Discipline Committee (RDC) 085722532973 roudho_
Division
Member of the Rules and
63. 101022330079 Geraldi Ridwan Hakim ALD Discipline Committee (RDC) 085224492559 geraldirh
Division
Member of the Rules and
64. 101022330180 Nicholas Sandy Kurniawan ION 089616614398 nic.id
Discipline Committee (RDC)

Algorithm and Programming Practical Module 2024/2025


xxii
Division

Member of the Rules and


65. 101022340248 Muhammad Favian Revaldy FAV Discipline Committee (RDC) 082240137674 hsystyc
Division
Member of the Rules and
66. 101052300002 Adelia Afriliani EKA Discipline Committee (RDC) 081278777815 aeluoi
Division
Member of the Rules and
ahsanihsan
67. 101022300119 Adzin Nabil Ihsan ZIN Discipline Committee (RDC) 082329451460
445
Division
Member of the Rules and
68. 101022300056 Nasywa Anggieta Tiara SYW Discipline Committee (RDC) 081220915625 nsywlb
Division
Member of the Rules and
justawildgu
69. 101052300119 Zaidan Abdurrahman Hakim DUN Discipline Committee (RDC) 082261203464
y
Division
Member of the Rules and
bukankasur
70. 101012340340 Aulia Rahma AUL Discipline Committee (RDC) 081220552616
sayamahal
Division
Member of the Rules and
wullan.nats
71. 101022330103 Wullan Natasya Elik WLN Discipline Committee (RDC) 081339008041
s
Division
Human Resource
farrelardya
72. 101012330102 Farrel Ardya Ghalyndra REL Development (HRD) 082113964165
g
Division Coordinator
Member of Human
73. 101012330351 Neil Justin Surupati TIN Resource Development 081287480761 sk.uy
(HRD) Division
Member of Human
samuelseni
74. 101062300038 Samuel Senin SAM Resource Development 085710845636
nn
(HRD) Division
Member of Human
Mohammad Fiqri
75. 101052300113 RYU Resource Development 082192986904 fiqri945
Firmansyah
(HRD) Division
Member of Human
76. 101012330067 Zaira Novika Adila ZAI Resource Development 0895613073427 lalaazaira
(HRD) Division
Member of Human
mr.ihsanak
77. 101022300129 M Raid Ihsan Akbar BAY Resource Development 082124072608
bar
(HRD) Division
Member of Human
78. 101042330086 Deannisaa Addysti Wahyudi DYS Resource Development 085524414622 dysti_705
(HRD) Division

Algorithm and Programming Practical Module 2024/2025


xxiii
Member of Human
79. 101022340029 Muhammad Ryan Pratama RYN Resource Development 085261820011 spideybae
(HRD) Division
Maintenance and Logistics
80. 101022300013 Bustan Nabiel Maulana BUS Committee (MLC) Division 081216919968 tanmln
Coordinator
Member of Maintenance
81. 101052300006 Aurelia Kanaya Keisha AKK and Logistics Committee 08888608122 aurelianaya
(MLC) Division
Member of Maintenance
82. 101022300124 Gibran Reza Al Ghazzali GND and Logistics Committee 085866405867 ghazzali14
(MLC) Division
Member of Maintenance
luqman076
83. 101052300102 Luqmanul Hakim NOE and Logistics Committee 082238264823
5
(MLC) Division

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

Algorithm and Programming Practical Module 2024/2025


xxiv
MODULE 1: INTRODUCTION TO ALGORITHM AND
PROGRAMMING

Objectives of the Practicum


1. Learn how to install Visual Studio Code.
2. Understand the concept of algorithms and their notations.
3. Understand the algorithm design of a program.
4. Understanding how to make a flowchart

1.1 Integrated Development Environment (IDE)


Integrated Development Environment (IDE) is a computer program that provides various
essential facilities needed to support efficient software development. IDE is designed to be the main
tool that integrates various functions and utilities needed by software developers in one centralized
platform. The main purpose of IDE is to simplify the development process, increase productivity,
and minimize errors by providing an integrated and easy-to-use working environment.
IDEs usually includes a variety of features designed to meet the needs of developers. Some
of the basic facilities that are generally found in an IDE includes:

• Editor, namely the facility for writingsource code of the software.


• Compiler, namely a facility to check the syntax of the source code and then change it into a
binary form that is compatible with machine language.
• Linker, namely a facility for combining binary data from several source codes generated
compiler so that the binary data becomes one unit and becomes a computer program that
is ready to be executed.
• Debugger, namely facilities for testing the running of programs to find bug/errors contained
in the program.

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.

1.2 Visual Studio Code Installation


1) After downloading Visual Studio Code, double-click on the installation file. Then select 'I accept
the agreement' and click Next.

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.

Algorithm and Programming Practicum Module 2024/2025


2
4) There are several types of installation options in the “Select Additional Tasks” menu. Check all
except the ' Add “Open with Code” ' option, 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.

7) Click Finish when the installation is complete.

8) Next, download the tdm-gcc compiler from the website https://jmeubank.github.io/tdm-gcc/

Algorithm and Programming Practicum Module 2024/2025


4
and download it according to your computer specifications.

9) Click on the Create button.

10) Next, select the edition according to your computer specifications.

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.

Algorithm and Programming Practicum Module 2024/2025


6
14) Another must-have extension is Code Runner, with which the C language can be run in Visual
Studio Code.

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

2. Go to Windows Security ->Threats and exclusions

3. Click the Manage Exclusions link to open the Exclusions window.

4. Click Add or remove exclusions

5. Add an exception in one of the following ways:

• Click Add an exclusion -> folder (This folder is used as a storage place for the program
to be run)

Algorithm and Programming Practicum Module 2024/2025


7
• Select or create a folder that will be used as a storage place for the program

If there is already an address name for the selected folder, then the folder exception
step has been completed.

1.3 Creating Simple Code


1) For the first step, please open Visual Studio Code, then select Open Folder.

Algorithm and Programming Practicum Module 2024/2025


8
2) After you select Open Folder, a new tab will appear, then select a folder to save your project,
then select Select Folder.

3) If a tab like the one above appears, select Yes, I trust the author.

Algorithm and Programming Practicum Module 2024/2025


9
4) Then click New File

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

Algorithm and Programming Practicum Module 2024/2025


10
1.4 Algorithm

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.

Perimeter = length + width + length + width

or
Perimeter = 2 x (length + width)

You can pour the algorithm as follows:


1. Enter the length and width values of the rectangle.
2. Calculate the perimeter of a rectangle using the formula 2x(length+width).
3. Display the perimeter value of the rectangle.

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)

Rectangle perimeter program

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.

Following are the standard symbols for flowcharts.

Form Symbol Name Description

Flow Line Expresses the flow of a process.

On-Page Declares a connection from one process to another on


Connectionr the same page.

Off-Page Declares a connection from one process to another on


Connector a different page.

Process Expresses an action (process) carried out by a computer.

Indicates a certain condition that will result in two


Decision
possibilities, namely YES or NO.

Expresses a beginning or end of


Terminator
a program.

Algorithm and Programming Practicum Module 2024/2025


12
Predefined State other procedures that have been created in the
Process diagram.

Expresses the input or output process


Input / Output
regardless of the type of equipment.

Declares initialization of variables,


Preparation
functions, libraries and others.

State comments or provide further


Annotation
explanation in the flowchart.

Example of a flowchart for calculating the area of a rectangle:

Algorithm and Programming Practicum Module 2024/2025


13
1.5 Basic Structure of C Programming
Here is an example of a simple program that will display the text “Hello World” on the output
terminal:

1 // Simple program to display text Flowchart for


2 #include <stdio.h> code:
3
4 /* int main() is the MAIN function,
5 and will be executed first by the program. */
6 int main() {
7 // Displays “Hello World”
8 printf("Hello World! \n");
9 return 0;
10 }// end of main function

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 (;).

The C language programming structure consists of:


• Comments

1 // Simple program to display text


… …
4 /* int main() is the MAIN function,
5 and will be executed first by the program. */
… …
10 }// end of main function

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.

Algorithm and Programming Practicum Module 2024/2025


14
• Preprocessor #include

2 #include <stdio.h>

In the C programming language, there is a special command called #include. This


command tells the computer to read the contents of another file, commonly called a "header" and
add it to our program. For example, the header file stdio.h. When we write #include <stdio.h>
at the beginning of the program, we tell the computer to use the basic functions in stdio.h, such as
printf() and scanf(). The contents of the header will be discussed further in module 5.

• 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

8 printf("Hello World! \n");

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.

Algorithm and Programming Practicum Module 2024/2025


15
• The scanf() Function and Introduction to Variables
Here is an example of a program:

1 // Simple program for input and output.


2 #include <stdio.h>
3
4 int main() {
5 // Declare an int variable named “var”
6 int var;
7
8 // Displays the text “Enter a number: ” on the output
9 printf(“Enter a number: ”);
10
11 // User inputs a number through the scanf() function
12 scanf(“%d”, &var);
13
14 // The program displays the results of user input.
15 printf(“The number entered is %d.”, var);
16
17 // Program ends
18 return 0;
19 }

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.

Algorithm and Programming Practicum Module 2024/2025


16
1.6 Debugging
Debugger usage:
1) Go to the sidebar then select Run and Debug or click F5.

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.

Algorithm and Programming Practicum Module 2024/2025


17
4) For example, if you click on it, a red dot will appear as in the picture.

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".

Algorithm and Programming Practicum Module 2024/2025


18
MODULE 2: BASIC SYNTAX AND STRUCTURE OF C
PROGRAMS

Objectives of the Practicum


1. Understand the general form of algorithms and their implementation in C language.
2. Create simple programs involving I/O, assignment, variables, constants, expressions,
and constructed data types.
3. Understanding data types in algorithms and their equivalents in C.

2.1 Variables and Constants


Variables and constants are names that indicate a place in computer memory and contain a
value. The contents of a variable can be changed at any time when the program is executed, while
constants cannot be changed when the program is executed. Variables and constants must be
declared first before they can be used in a program. Examples of constant and variable declarations
are as follows:
// Declare a constant using “#define”.
#define g = 9.8

// Declare constants using “const”.


const int height = 10;

/*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;

// Variable values can also be directly assigned like constants.


int radius = 7, diameter = 14;

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.

Algorithm and Programming Practicum Module 2024/2025


19
Here is an example of the use of variables and constants:
1 // Simple program for input and output.
2 #include <stdio.h>// declare header
3
4 // Declare a constant named “pi” with the value 3.14
5 #define pi 3.14
6
7 int main() {
8 // Declare multiple variables in the same line
9 int var1, var2;
10
11 // Display the text “Enter the first number: ” on the output
12 printf(“Enter the first number: ”);
13
14 // User inputs a number through the scanf() function
15 scanf(“%d”, &var1);
16
17 // Display the text “Enter the first number: ” on the output
18 printf(“Enter the second number: ”);
19
20 // User inputs a number through the scanf() function
21 scanf(“%d”, &var2);
22
23 // The program displays the results of user input.
24 printf(“The numbers entered are %d and %d.”, var1, var2);
25
26 // Program ends
27 return 0;
28 }

Example of input and output from the program above: (input is marked with UNDERLINE text)

Enter the first number: 25


Enter the second number: 10
The numbers entered are 25 and 10.

• 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.

Algorithm and Programming Practicum Module 2024/2025


20
The second argument, &var1, is the location where the value entered by the user will be
stored. The & sign in C when combined with the variable name, which in this case is var1, will take
the address of the variable var1 in memory, and will store the value entered by the user at that
memory address.

Adding values to variables


There are 3 ways to enter values into variables, namely:
❖ Assignments(values are entered into variables directly)
int a = 6;
char letter = 'A';
char sentence[10] = “Daskom”;

❖ Inputusing the scanf() command


C Input and Output
1 #include <stdio.h> INPUT (UNDERLINED)
2 int main () Number 1 = 10
3 { Number 2 = 6
4 int x,y,z;
5 printf(“Number 1 = “); OUTPUT
6 scanf (“%d”,&x); Number 1+Number 2= 16
7 printf(“Number 2 = “);
8 scanf(“%d”,&y);
9 z=x+y;
10 printf(“Number 1+Number 2=
%i\n”,z);
11 returns 0;
12 }

#define is used to define a variable (input - output


❖ Use of constants pins, etc.) with a new variable name so that when
C creating a program, it is easier to remember the
#include <stdio.h> variable name. Therefore, when defining a
#define phi 3.14 variable, try to use a variable name that reflects its
#define name “Brian” function.
#define letter 'b'
int main ()
{
int r;
wide float;
printf(“Radius of Circle =“);
scanf (“%d”,&r);
%.xf is used to display x numbers
area = phi*r*r; behind the comma of the output
printf("Area of Circle =%.2f\n”,area); variable. In the example above,
return 0; printf(“Area of Circle = %.2f
} \n”,area); will display 2 numbers
behind the comma of the area
variable.

Algorithm and Programming Practicum Module 2024/2025


21
2.2 Data Types
Data type is the type of a variable used in an algorithm. Here are some types of data types.
a. Int: Represents an integer between -32768 to +32767.
Example: 1 0 3 -5
b. Float: Expresses real numbers (natural numbers) from 10-38 up to 1038.
Example: 1.1, 1.3, -9.2
c. Character: Declares a character.
Examples: A, f, 9, or *.

d. Bool: Declares a logical value of true or false.

Data Type Format Specifier


Integer %d, %i
floating point
• decimal form %f
• rank form %e
• which is shorter between decimal and exponent %g
double precision %lf
Character %c
String %s
unsigned integer %u
long integer %ld
long unsigned integer %lu
unsigned hexadecimal integer %x
unsigned octal integer %o

Algorithm and Programming Practicum Module 2024/2025


22
By default, the C language displays decimal numbers with 6 digits after the comma. This
means that if what is written is 4.323, then what is displayed is 4.323000. The printf command has
special rules to regulate the C language to display the number of digits after the comma. We can
add 3 ways of writing to the %f pattern. Where the format is as follows:
Format
%f Will display 6 digits after the decimal point.
%xf Will display a number of x digits with spaces as separators.
%0xf Will display a number of x digits with 0 as a separator.
%.xf Will display x digits after the decimal point

*Note that x is filled with the desired number.

2.3 Arithmetic Operations


For arithmetic operations only int and float data types can be used. The following arithmetic
operators are available:
1) Multiplication ( * )
Used to multiply two numbers.
2) Division ( / )
Used to divide two numbers.
3) Addition ( + )
Used to add two numbers.
4) Subtraction ( - )
Used for subtraction between two numbers.
5) Modulo/Mod ( % )
Used to find the remainder of the division of two numbers. The mod operator in C is “%”.
The mod operation can only be used by data of type int.

Data Type Example


6%4=2 {6=4x1+2}
8%5=3 {8=5x1+3}
Int % Int = Int
-5 % 3 = -2 { -5 = 3 x (-1) + (-2) }
-3 % 2 = -1 { -3 = 2 x (-1) + (-1) }

Algorithm and Programming Practicum Module 2024/2025


23
Coding Input and Output Flow chart

1 #include <stdio.h> INPUT


2 Enter the radius of the
3 int main() circle = 7
4 {
5 // Declare variables and OUTPUT
constants Area of circle = 153.86
6 const float phi = 3.14;
7 float r;
8 float area;
9
10 // Enter the radius
11 printf(“Enter the radius
of the circle = ”);
12 scanf(“%f”, &r);
13
14 // Calculate area
15 area = phi * r * r;
16
17 // Output the area of a
circle
18 printf(“Area of circle =
%.2f \n”, area);
19
20 return 0;
21 }

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.

Algorithm and Programming Practicum Module 2024/2025


24
Coding Input and Output Flow chart

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.

Algorithm and Programming Practicum Module 2024/2025


25
Coding Input and Output Flow chart

1 #include <stdio.h> INPUT


2 Name : David
3 // Form data type Major : EE
4 struct biodata ID : 1010
5 { Class : EL08
6 // Declare variables in a struct
7 char name[20], major[20], OUTPUT
studentID[20], class[20]; Name : David
8 } b; // Variables for struct Major : EE
9 ID : 1010
10 int main() Class : EL08
11 {
12 // Input Name
13 printf("Name\t: ");
14 gets(b.name);
15
16 // Input Major
17 printf("Major\t: ");
18 gets(b.major);
19
20 // Input NIM
21 printf("NIM\t: ");
22 gets(b.studentID);
23
24 // Class Input
25 printf("Class\t: ");
26 gets(b.class);
27
28 // Output
29 printf("Your biodata: \n");
30 printf("Name\t: %s \n", b.name);
31 printf("Major\t: %s \n",
b.major);
32 printf("NIM\t: %s \n",
b.studentID);
33 printf("Class\t: %s \n",
b.class);
34 return 0;
35 }

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.

Algorithm and Programming Practicum Module 2024/2025


26
Coding Input and Output Flow chart

1 #include <stdio.h> INPUT


2 struct modulo Number 1 % Number 2
3 { Example Input:
4 // Declare variables in 10 4
struct Modulo Result: 2
5 int x, y;
6 }; Enter Number:
7 9 5
8 int main() Modulo Result: 4
9 {
10 // Declare a struct
variable
11 struct modulo mod;
12
13 // Displays the sentence
14 printf("Number 1 %%
Number 2\n");
15 printf("Example Input:
\n");
16 printf("10 4 \n");
17
18 // Display “Modulus
Result”
19 printf("Modulo Result:
2\n");
20
21 // Enter a number
22 printf("Enter a number:
\n");
23 scanf("%d %d", &mod.x,
&mod.y);
24
25 // Display the results
26 printf("Modulo Result:
%d", mod.x % mod.y);
27 return 0;
28 }

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.

Algorithm and Programming Practicum Module 2024/2025


27
MODULE 3: PROGRAM FLOW CONTROL

Objectives of the Practicum


1. Able to write if, if-else, and switch case statements to make decisions in a
program.
2. Able to write if, if-else, and switch case statements to make decisions in a
program.
3. Solve cases regarding branching and implement them in C.

3.1 Logical and Relational


Boolean operations are logical operations that will only produce true or false values. This operation
will often be used to determine the action to be performed by the program (in branching or looping).
The boolean data type is required to use the stdbool.h header. The stdbool.h header in the C
language functions to perform operations related to boolean expressions.

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

Algorithm and Programming Practicum Module 2024/2025


28
3.2 If – Else
The if command is a type of branching that will execute an action if the condition is true. if-
else is used when there is only one condition, while if-else if-else is used when there are
two or more conditions.
Basic Structure:
if [condition] – – [action]
else if [condition] – – [action]
else – – [action]

Example:
if (height >= 140) {
printf(“VALID!”);
printf(“Please enter”);
} else {
printf(“INVALID!”):
}

The above example can be interpreted as:


If the height is greater than or equal to 140,
then the program will display VALID! Please login
In addition, it will display INVALID!
The following is an example of implementation in C language.
a. One action
C Input and Output Flow chart
1 #include <stdio.h> EVEN EXAMPLE:
2 int bil; INPUT
3 void main() Number: 10
4 {
5 printf("Number: "); OUTPUT
6 scanf("%d", &bil); Even Number
7
8 // Branching, if the entered
number has no remainder
when divided by 2, then the ODD EXAMPLE:
number is even. INPUT
9 if (bil%2 == 0) Number: 25
10 {
11 printf("Even Number"); OUTPUT
12 } Odd Number
13 // If the entered number has
a remainder when divided by
2, then it is an odd
number.
14 else printf("Odd Number");
15 }
Algorithm and Programming Practicum Module 2024/2025
29
The program above is an example of a program with one action, the program will display
"Even Number" if the value of the number entered is even (a number that is divisible by 2 or the
number %2 = 0), otherwise the program will display "Odd Number" if the condition is 'if ' is not
fulfilled.
b. Two actions
C Input and Output Flow chart
1 #include <stdio.h> EXAMPLE OF
2 #include <string.h> SUCCESSFUL LOGIN
3 INPUT
3 // Declare variables Username : Looping
4 char user[50],pass[50]; Password : Forever
5 int main()
6 { OUTPUT
7 // Enter username and Login Success
password Please Continue
8 printf("Username : ");
9 gets(user); EXAMPLE OF FAILED
10 printf("Password : "); LOGIN
11 gets(pass); INPUT
12 Username : Daskom
13 // Do the username and Password : Lab
password match the
answers? OUTPUT
14 if (strcmp(user, Login Failed
"Looping") ==0 &&
strcmp(pass, "Forever")
==0){
15 // Login successful
if the answer matches
16 printf("Login
Successful\n");
17 printf("Please
Continue\n");
18 }
19 // Login fails if not
matched
20 else printf("Login
Failed\n");
21 return 0;
22 }

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.

Algorithm and Programming Practicum Module 2024/2025


30
C Input and Output
1 #include <stdio.h> EXAMPLE OF SUCCESSFUL LOGIN
2 #include <string.h> INPUT
3 Login User!
4 // Declare variables for correct username and Username : me
password Password : login
5 char user[50] = "me";
6 char pass[50] = "login"; OUTPUT
7 Login Success
8 int main() Please Continue
9 {
10 // Declare variables for user input Login User!
11 char username [50], password [50]; Username : me
12 Password : logout
13 printf("Login User!\n");
14 OUTPUT
15 // User enters username and password Login Success
16 printf("Username : "); gets(username); Please Continue
17 printf("Password : "); gets(password);
18
19 // If either the username or password is EXAMPLE OF FAILED LOGIN
correct, then the login will be INPUT
successful. User Login!
20 if (strcmp(user, username) ==0 || Username : I
strcmp(pass, password) ==0) Password : logout
21 {
22 printf("Login Successful\n"); OUTPUT
23 printf("Please Continue\n"); Login Failed
24 }
25 // If both username and password are wrong,
then login will fail.
26 else printf("Login Failed\n");
27 return 0;
28 }
Similar to the previous code, the program above will display “Login Successful” if the
username OR password entered matches the one in the program line above, namely “me” and
“login”.
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 “aku” OR if the password entered is the
same as “login”, then the program will perform the if action, namely “Login Successful” and “Please
Continue”. This means that the operator “||“ was successfully performed with one true condition.
Note:
- If there is more than one action (in if or else) to be carried out, then add “{“ (before the first
action) and “}” (after the last action).
- Cannot use “==” sign to compare strings.
- The comparison is done using the function strcmp(). Function strcmp()located in the header
#include <string.h>.

Algorithm and Programming Practicum Module 2024/2025


31
- On function strcmp(string1, string2) There are several return values, including:
0 : if string1 is equal to string2
<0 : if string1 is smaller than string2
>0 : if string1 is greater than string2

3.3 Switch Case


Switch case is a type of branching that allows for several conditions at the same time. In this
branching there are three commands, namely switch, case, and default. Switch will receive a variable
value, then will see that the variable value is included in the case. If it is a case, then the program will
run the command, if not then the program will run the command on the default command.
Structure:
switch (variable){
case 1:
[action]
break;
case'A':
[action]
break;
default:
[action]
}
C
1 #include <stdio.h>
2
3 // Declare variables
4 int i;
3
4 void main ()
5 {
6 // Enter the desired day order
7 printf("Enter the day sequence: ");
8 scanf("%d",&i);
9
10 // Switch case with variable i
11 switch (i)
12 {
13 // The program compares the value of i with each case.
14 case 1:
15 printf("Monday"); break;
16 case 2:
17 printf("Tuesday"); break;
18 case 3:
19 printf("Wednesday"); break;
20 case 4:
21 printf("Thursday"); break;
22 case 5:
23 printf("Friday"); break;
24 case 6:
25 printf("Saturday"); break;
26 case 7:
Algorithm and Programming Practicum Module 2024/2025
32
27 printf("Sunday"); break;
28 default:
29 printf("Number out of sequence 29days");break;
30 }
31 }

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.

Algorithm and Programming Practicum Module 2024/2025


33
MODULE 4: LOOPING AND ITERATION

Objectives of the Practicum


1. Understanding the form of repetition.
2. Can create simple programs using loops with C language.
3. Solve a case regarding looping and implement it in C language.

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.

Pre-Increment and Post-Increment


These two terms are ways to add value to a variable.
• post increment
returns the value to a value that has not undergone an addition operation (the value is output
first, then added).
• pre-increment
returns the value to the value that has undergone an addition operation (the value is added
first, then output).

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:

• Initialize the value i = 0.

• The first printf command is used to check the initial value of the variable i.

• In the post-increment command (i++) the value i=0 is produced because


the value is output first, then added. When calling the result of i again, the
value of i is already 1.

• 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.

4.2 Types of Looping

The following are the types of loops in the C programming language:


1. While loop
In this method, the action will be performed as long as the condition is true and will stop if
the condition becomes false. In this loop, the number of loops is not known for sure.
Declaration:
while(condition)
{
// action
// action
// action
// update statement
}

Example:
while (i < 3){
printf(“%d ”, i);
i++;
}

Algorithm and Programming Practicum Module 2024/2025


35
This example will display the output: 0 1 2, assuming the initial value of i = 0. At i = 0 (the
first iteration), the program will display the current value of i and will add one to the value
of i with the command “i++”, so that the value of i becomes 1. Then at i = 1 (the second
iteration), the program will display the current value of i and will add one to the value of i
with the command “i++”, so that the value of i becomes 2. The program will perform the
same commands until the condition is no longer TRUE.

C Flow chart Output


1 #include<stdio.h> 1
2 2
3 // Declare variable i 3
4 int i; 4
5
5
6 void main()
6
7 {
8 7
9 // Assign the value of i to 1 8
10 i=1; 9
11 10
12 // The loop starts by checking
the condition i<=10
13 while(i<=10)
14 {
15 // Display data i
16 printf(“%d\n”,i);
17
18 // Value of i is increased
by 1
19 i=i+1;
20 }
21 }

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.

Algorithm and Programming Practicum Module 2024/2025


36
Declaration:
do {
// action
// action
// action
// update statement
} while(condition)

C Flow chart Output


1 #include <stdio.h> 1
2 2
3 // Declare variable i
3
4 int i;
5 4
6 void main (){ 5
7 // Assign value i = 1 6
8 i=1; 7
9 do {
8
10 // Display the value
of i 9
11 printf("%d \n",i); 10
12
13 // Add the value of i
14 i++;
15 }
16 // Checking condition
17 while (i<=10);
18 }

Notes:
• The i++ statement is identical to i=i+1;

Algorithm and Programming Practicum Module 2024/2025


37
3. For loop
In this loop, the number of loops is known for sure (Counted Loop). This loop is used
if we already know how many loops will be performed.

Declaration:
for(initialization; condition; update statement){
// action
// action
// action
}

C Flow chart Output


1 #include<stdio.h> 1
2 2
3 // Declare variable i 3
4 int i; 4
5
5
6 void main(){
6
7 // Assign the value of
i, check the condition,
7
and update the
statement
8 for (i=1; i<8; i++)
9
10 // Display i
11 printf("%d \n",i);
12 }

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

Algorithm and Programming Practicum Module 2024/2025


38
C Flow chart
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 // Declare variables
5 int value,n,i;
6 char name[100];
7
8 void main()
9 {
10 // Clear the terminal screen
11 system("cls");
12
13 // Enter the amount of data
14 printf("Number of Data : ");
15 scanf("%d",&n);
16
17 // Initialize for loop
18 for (i=1;i<=n;i++)
19 {
20 // User enters name and value
21 printf("Value");
22 scanf("%d",&value); getchar();
23 printf("Name : "); gets(name);
24 }
25 }

system(“cls”); serves to clear the The getchar() function is found in the


program screen. system(“cls”) is found in stdio.h library
the stdlib.h library

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.

Algorithm and Programming Practicum Module 2024/2025


39
4.3 Control Commands

Control commands are used in loops to change the result of loop execution from its normal state.
Below are the control commands in loops:

Commands Example Program Output Information


#include<stdio.h> 1 The break command is used
2 to stop the ongoing looping
int i; 3
void main(){ process. In the example
Break 4
for(i=1;i<10;i++){ above, the loop will stop
Command 5
if(i==7)break;
6 when i = 7.
printf("%d\n",i);
}
}
#include<stdio.h> 1 The continue command is
2 used to skip the intended
int i; 3
void main(){ loop. In the example above,
4
for(i=1;i<10;i++){ the program will continue
Continue 5
if(i==7)continue; the loop when i = 7.
Command printf("%d\n",i);
6
}
8
} 9

Algorithm and Programming Practicum Module 2024/2025


40
MODULE 5 : FUNCTIONS

Objectives of the Practicum


1. Understand the use of functions in C language.
2. Understanding the function structure in C language.
3. Can distinguish between types of function parameters in C language.
4. Can create programs using functions in the C language.

5.1 Standard Library Functions


In C language, there are many functions that have been defined in the C Standard Library,
such as <stdio.h>, <string.h>, <math.h>, and many others. Here are some examples of libraries in
the C Standard Library and some examples of functions defined in them.
1. Standard Input Output Library (stdio.h)
This library provides basic functions for input and output, such as printf() to display output to
the screen and scanf() to read input from the user.

2. String Manipulation Library (string.h)


This library provides functions for manipulating strings such as:
• strcpy(): Copy a string.
• strlen(): Calculates the length of a string.
• strcmp(): Compares two strings.

3. Standard Library (stdlib.h)


This library provides various utility functions, including memory management, number
conversion, and process control, including:
• system(“cls”): Clears the terminal output screen
• system(“pause”): Pauses the program
• exit(): Terminates the program

4. Mathematics Library (math.h)


This library provides basic mathematical functions such as:
• sin(): Sine function
• cos(): Cosine function
• tan(): Tangent function.
• sqrt(): Calculates the square root.
• pow(): Calculates the exponent.

5. Ctype Library (ctype.h)


This library provides functions for character inspection and manipulation. Examples:
• isdigit(): Checks if a character is a digit.

Algorithm and Programming Practicum Module 2024/2025


41
• isalpha(): Checks if a character is a letter.
• toupper(): Changes a character to uppercase.
• tolower(): Changes a character to lowercase.

6. Time Library (time.h)


This library provides functions for manipulating time and date. Examples:
• time(): Returns the current time.
• clock(): Returns the CPU time used by the program.
• difftime(): Calculates the difference between two times.

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

Local Variable intplus(int a, int b){


int result;
result=a+b;
return result;
}

Algorithm and Programming Practicum Module 2024/2025


42
A function is a piece of code that is intended to perform a specific task. This task requires input
information called parameters and usually a function will return a value (return value).
In writing a function, a name/identifier is given, formal parameters (input values that are also
named and their types are described), and the type of the function is declared. Functions can be
created before or after writing the main program. If created after writing the main, then the function
prototype must be written at the top of the program.

How to Call a Function C Algorithm


Assignments a = add(x,y) a  add(x,y)
Output(printf) printf(“%d”,add(x,y)) Output(add(x,y))

a. Writing functions after the main program


This way of writing requires a function prototype, the purpose is as an abstract so that the
function can be recognized by the entire program. The function prototype only requires the data
type of its parameters, so we don't have to write the variables.
C
1 #include <stdio.h>
2 int count(int x, int y); //Function Prototype
3 int main(){
4 int total, discount, total_discount, total_cost;
5 printf("===DISCOUNT CALCULATING PROGRAM===\n");
6 printf("Enter actual cost: Rp. ");
7 scanf("%d", &total);
8 printf("Enter the discount received (%) : ");
9 scanf("%d", &discount);
10 total_discount = count(total, discount); //actual parameters
11 printf("The discount you get = Rp. %d\n", total_discount);
12 total_cost = total-total_discount;
13 printf("Cost after discount = Rp. %d",total_cost);
14 return 0;
15 }
16
17 int count(int x, int y){ //count = identifier, (int x,int y) = formal
parameters
18 int discount_cost;
19 discount_cost = (x*y)/100;
20 return discount_cost; //Return Value
21 }

b. Writing functions before the main program


If the function is written before the main function, then the function prototype is not needed.
This is because the compiler already recognizes the function when reading the main function.
C
1 #include <stdio.h>

Algorithm and Programming Practicum Module 2024/2025


43
2 int count(int x, int y){ //count = identifier, (int x,int y) = formal
parameters
3 int discount_cost;
4 discount_cost = (x*y)/100;
5 return discount_cost; //Return Value
6 }
7
8 int main(){
9 int total, discount, total_discount, total_cost;
10 printf("===DISCOUNT CALCULATING PROGRAM===\n");
11 printf("Enter actual cost: Rp. ");
12 scanf("%d", &total);
13 printf("Enter the discount received (%) : ");
14 scanf("%d", &discount);
15 total_discount = count(total, discount);//actual parameters
16 printf("The discount you get = Rp. %d\n", total_discount);
17 total_cost = total-total_discount;
18 printf("Cost after discount = Rp. %d",total_cost);
19 return 0;
20 }

Output
Example :

Enter Actual Cost: Rp. 100000


Enter the discount received (%) : 60

The discount you get = Rp. 60000


Cost after discount = Rp. 40000

Flow chart

Algorithm and Programming Practicum Module 2024/2025


44
5.3 Void Function/Procedure (Void Function)
A procedure function is a function that does not return a value. Procedure functions are
used to perform specific tasks without returning results to the caller. They are often used to perform
actions such as printing output, changing the value of a global variable, or modifying parameters
passed by pointer.
C Output
1 #include <stdio.h> Example 1:
2 Number: 10
3 void number(int a){ Positive
4 if(a>0) printf("Positive");
5 else if(a<0) printf("Negative"); Example 2:
6 else printf("Zero"); Number: -22
7 } Negative
8
9 void main(){ Example 3:
10 int x; Number: 0
11 printf("Number: "); Zero
12 scanf("%d", &x);
13 number(x);
14 }
Flow chart

5.4 Recursive Algorithms


Recursion is an algorithm that calls itself. Algorithms that are recursive are called recursive.
Recursion can only be used on procedures and functions, this is because only procedures and
functions can be called. In general, recursion can be illustrated as a regular iterative algorithm but
using functions and procedures.

Algorithm and Programming Practicum Module 2024/2025


45
Following are important terms in recursion.
• Base: conditions that will stop the recursive process.
• Recurrence: a command that will call the recursive algorithm itself (in this case a procedure
or function).
The following is an example of using a recursive algorithm to find the factorial value.
C Input and Output
1 #include <stdio.h> INPUT (BOLD)
2 int nFactorial(int n); FACTORIAL FUNCTION
3 int x, result; Please enter a number: 5
4 int main(){
5 printf("FACTORIAL FUNCTION\n"); OUTPUT
6 printf("Please enter a number: "); Factorial result: 120
7 scanf("%d",&x); getchar();
8 result = nFactorial(x);
9 printf("Factorial result:
%d",result);
10 return 0;
11 }
12
13 int nFactorial(int n){
14 if (n==1 || n==0){//Base
15 return 1;
16 }
17 else if (n>1) {
18 return n * nFactorial(n-1);
19 //Recurrence
20 }
21 }
Flow chart

Algorithm and Programming Practicum Module 2024/2025


46
MODULE 6: ARRAYS AND STRINGS

Objectives of the Practicum


1. Understand the purpose of using arrays.
2. Can create programs using one / two dimensional arrays.
3. Can create programs using two-dimensional arrays.
4. Understand the basic principles of how strings work in C language.
5. Understanding the difference between strings as arrays of characters and
pointers-to characters.
6. Able to manipulate a string with various processing methods provided.

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.

Without Array With Array


1 #include <stdio.h> 1 #include <stdio.h>
2 2
3 int data1, data2, data3, data4, 3 int data[100], i, n;
data5, data6; 4
4 5 int main(){
5 int main() { 6 n = 5;
6 printf("Data Number 1 : "); 7 for (i = 0; i <= n; i++) {
7 scanf("%d", &data1); 8 printf("Data Number %d : ", i+1);
8 printf("Data Number 2 : "); 9 scanf("%d", &data[i]);
9 scanf("%d", &data2); 10 }
10 printf("Data Number 3 : "); 11 }
11 scanf("%d", &data3);
12 printf("Data Number 4 : ");
13 scanf("%d", &data4);
14 printf("Data Number 5 : ");
15 scanf("%d", &data5);
16 printf("Data Number 6 : ");
17 scanf("%d", &data6);
18 }

Algorithm and Programming Practicum Module 2024/2025


47
Flowchart

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.

Algorithm and Programming Practicum Module 2024/2025


48
6.2 One Dimensional Array
As the name implies, a 1-dimensional array is an array that only has 1 dimension. Imagine
an array as a collection of lockers lined up in a row. Each box stores a value and each box has its
own sequence number. cannot be filled with more than 5 data.

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

Array elements (contents of each locker) 5 10 7


Array [5] may contain < 5 data,
Array index (locker number) → 0 1 2 3 4

Array elements (contents of each locker) 5 10 7 2 11 8 Array[5] cannot


Array index (locker number) → 0 1 2 3 4 5 contain >5 data

Example program using one-dimensional array:

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

Algorithm and Programming Practicum Module 2024/2025


49
Arrays can also be used to store data with a form type or struct. As in the example
below, where the array is used to store student data consisting of the name, student ID,
and student grades.
Array of struct
#include <stdio.h>

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.

Algorithm and Programming Practicum Module 2024/2025


50
Array of char
#include <stdio.h>
#include <string.h>

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.

6.3 Multidimensional Arrays


Multidimensional arrays, as the name suggests, have more than one dimension. In
a one-dimensional array, the array only stores data in rows like the previous example. In a
multidimensional array, the array has both row and column dimensions.
The following is an example of a declaration for a two-dimensional array:
int number[5][10];

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)

Example program using two-dimensional array:

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

Algorithm and Programming Practicum Module 2024/2025


52
6.4 String
String is a type of data type that contains a collection of characters of the unsigned char
data type that are collected into one, and is one way for us to be able to store data that contains
various characters that are combined into a "word" or "sentence" for humans, and of course these
characters have been recognized according to the ASCII standard (American Standard Code for
Information Interchange). In a given string, we need to know that one character it contains is one
byte (in memory units or RAM), so we can conclude that if given a string whose length (number of
letters) is 1,024 characters, then the program requires 1,024 bytes of memory space or RAM.

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>

Functions and Declarations Explanation


1. Copying: ...
memcpy() Copies the value of num bytes from the location pointed
void* memcpy(void to by source directly to the memory block pointed to by
*destination,const void
destination.
*source,size_tnumber);
move() Copies the value of num bytes from the location pointed
void* move(void to by source to the memory block pointed to by
*destination,const void
destination. Copying occurs as if an intermediate buffer
*source,size_tnumber);
were used, allowing destination and source to overlap.

strcpy() Copies the C string pointed to by source into the array


char* strcpy(char pointed to by destination, including the terminating NULL
*destination,const char
character (and stops at that point).
*source);
strncpy() Copies the first num characters from source to
char* strncpy(char destination. If the end of the source C string (marked by
*destination,const char
a NULL character \0) is encountered before the number
*source,size_t number);

Algorithm and Programming Practicum Module 2024/2025


53
of characters copied, the destination is padded with zeros
\0 until a total of num characters have been written to it.
2. Merger: ...
strcat() Appends a copy of the source string to the destination
char* strcat(char string. The terminating NULL \0 character at the
*destination,const char
destination is overwritten by the first character from the
*source);
source, and the NULL \0 character is included at the end
of the new string formed by concatenating the two at the
destination.
strncat() Adds the first number of characters from source to
char*strncat(char destination, plus a terminating NULL \0 character. If the
*destination,const char
length of the C string in source is less than num, only the
*source,size_tnumber);
contents up to the NULL \0 character will be copied.
3. Comparison: ...
memcmp() Compares the first num bytes of the memory block
int memcmp(const void pointed to by ptr1 with the first num bytes pointed to by
*ptr1,const void *ptr2,size_t
ptr2, returning zero (true) if they match or a value
number);
different from zero (false) indicating whichever is greater
if they do not match. The return principle above also
applies to the two explanations below.
strcmp() Compares C string str1 with C string str2. This function
intstrcmp(const char starts by comparing the first character of each string. If
*str1,const char *str2);
they are equal to each other, it continues with the next
pair until the characters are different or until a terminating
NULL \0 character is reached.
strncmp() Compares up to the number of characters in C string str1
intstrncmp(const char with C string str2. This function starts by comparing the
*str1,const char
first character of each string. If they are equal to each
*str2,size_tnumber);
other, it continues with the next pair until the characters
are different, until a NULL character \0 is reached, or until
the number of characters matches in both strings,
whichever comes first.
4. Search: ...
memchr() Searches in the first num bytes of the memory block
const void*memchr(const void pointed to by ptr for the first occurrence of value
*ptr,intvalue,size_tnumber);
(interpreted as an unsigned char), and returns a pointer
void*memchr(void
to it. Value and each byte examined in the ptr array are
*ptr,intvalue,size_tnumber);
interpreted as unsigned char for comparison.

strchr() Returns a pointer to the first occurrence of the character


const char* strchr(const char in the C string str. The terminating NULL character \0 is
*str,intcharacter);

Algorithm and Programming Practicum Module 2024/2025


54
char* strchr(char considered part of the C string. Therefore, it can also be
*str,intcharacter); used to retrieve a pointer to the end of the string.
strstr() Returns a pointer to the first occurrence of str2 in str1, or
const char*strstr(constchar a NULL pointer if str2 is not part of str2. The matching
*str1,const char *str2);
process does not include the terminating NULL character
char*strstr(char *str1,const
\0, but stops there.
char *str2);
5. Other/Additional: ...
memset() Sets the first num bytes of the memory block pointed to
void*memset(void by ptr to the specified value (interpreted as unsigned
*ptr,intvalue,size_t number);
char).
strerror() Interprets the value of errnum, producing a string with a
char*strerror(interror); message describing the error condition as if it were set to
errno by a library function (see note below). The returned
pointer points to a statically allocated string, which must
not be changed by the program. Further calls to this
function may overwrite its contents (a specific library
implementation is not required to avoid data races)
Note: You can use the standard header file <errno.h> to
facilitate the process of tracking systematic problems
experienced.
strlen() Returns the length of the C string str. The length of a C
size_t strlen(const char string is determined by the terminating NULL character or
*str);
\0: A C string is the length of the number of characters
between the beginning of the string and the \0 character
(excluding the terminating NULL character or \0 itself).
6. Macros and Data Types: ...
NULL This macro expands to the null pointer constant.
Definition:(void*)(0) Simply put, nothingness or nihility.

A null pointer constant can be converted to any pointer


type (or pointer-to-member type), which obtains the null
pointer value. This is a special value that indicates that the
pointer does not point to any object.
size_t An alias of one of the unsigned int types, as in the
Definition: definition below.
typedef unsigned long long
size_t
This is a type capable of representing the size of any
object in bytes: size_t is the type returned by the sizeof
operator and is widely used in various standard libraries
to represent sizes and quantities.

Algorithm and Programming Practicum Module 2024/2025


55
Strings in C language are divided into two forms of declaration, namely with the array of
characters method and pointer-to characters. Just a note, the pointer-to characters string variable
type will be studied in the next module on Pointers, so this module will only focus on processing
strings using an array of characters. The writing syntax is as follows:

#define BUFSIZE 100


char my_string[100],my_other_string[BUFSIZE];// BUFSIZE = 100
The variable above is named my_string which has been initialized to be able to hold as many
as 100 characters (the initialized number must be of the int data type, or can be declared
first using a constant definition, as in the example above in the variable my_other_string).

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.

Method 1: Copying and Concatenating Strings


Required functions: strcpy()or strncpy(), strcat() or strncat()

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.

Program Code Input and Output


1 #include <stdio.h> === Input ===
2 #include <string.h>

Algorithm and Programming Practicum Module 2024/2025


56
3 Insert a string (~20
4 int main(void) { letters): Daskom Lab
5 char src[20 + 1];
6 char dst_1[40 + 1], dst_2[40 + 1]; === Output ===
7 Source: Daskom Lab
8 printf("Insert a string (~20 letters): "); Destination 1: Daskom Lab
9 fgets(src, 20, stdin); is absolutely amazing!
10 src[strlen(src) - 1] = '\0'; Destination 2: Daskom Lab
// Reason to remove the newline '\n' is a fun experiment!
because
11 // of the after-effect of using fgets(). === Explanation ===
12 dst_1 is the result of
13 strcpy(dst_1, src); copying src and combining
14 strncpy(dst_2, src, 40); the string “is really
15 strcat(dst_1, " is absolutely amazing!"); amazing!”. Likewise with
16 strncat(dst_2, " is a fun experiment!", dst_2 which is also the
40); result of copying src and
17 combining the string “is a
18 printf("Source: %s\n", src); fun experiment!”.
19 printf("Destination 1: %s\n", dst_1);
20 printf("Destination 2: %s\n", dst_2);
21
22 return 0;
23 }

Method 2: String Comparison


Required functions: strcmp() or strncmp()
In addition to copying and combining the two strings with each other, string processing can
also be in the form of comparing one string with another. With the same provisions, the source
string will be compared with the destination string to find the differences. This comparison process
has been done automatically through the program, so that we only need to focus on the output
results given, which are worth 0 if the source string with the destination string are the same, and will
be worth other than 0 (can be -1 or 1 for example) if there is a difference between the two strings
when compared.

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.

Program Code Input and Output


1 #include <stdio.h> === Input ===
2 #include <string.h> Insert any password:
3 Admin#1234
4 int main(void) { Insert the password again:
5 char pass_1[20 + 1], pass_2[20 + 1]; admin#1234

Algorithm and Programming Practicum Module 2024/2025


57
6
7 printf("Insert any password: "); === Output ===
8 fgets(pass_1, 20, stdin); Both passwords are NOT the
9 pass_1[strlen(pass_1) - 1] = '\0'; same
10
11 printf("Insert the password again: "); === Explanation ===
12 fgets(pass_2, 20, stdin); pass_1given the input
13 pass_2[strlen(pass_2) - 1] = '\0'; “Admin#1234” and pass_2
14 if (strcmp(pass_1, pass_2) == 0) { given the input “admin#1234”
15 printf("Both passwords are the same!\n"); which are both 11 bytes in
16 } else { size. However, if checked,
17 printf("Both passwords are NOT the it can be seen that the
same!\n"); character 'A' in pass_1 has
18 } a value of 65, while the
19 character 'a' in pass_2 has
20 // Try to experiment individually by using a value of 97, until exiting
21 // strncmp(). Pay attention for how to strcmp() it has a value of
22 // distinguish the differences just like the not 0, aka false. (see
23 // first method before! (see table 7.1) reference: ASCII Table)
24 return 0;
25 }

Method 3: Search and Other String Manipulations


Required functions: strlen(), strchr(), and strstr()

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.

Finding the Length of a String

Program Code Input and Output


1 #include <stdio.h> === Input ===
2 #include <string.h> Insert a laboratory name: Dasar Komputer

Algorithm and Programming Practicum Module 2024/2025


58
3
4 int main(void) { === Output ===
5 int str_len; String length: 14
6 char lab_name[30 + 1];
7 === Explanation ===
8 printf("Insert a laboratory According to the explanation in the first
name: "); 3 paragraphs of method above, the
9 fgets(lab_name, 30, stdin); strlen() function is useful for measuring
10 lab_name[strlen(lab_name) - 1] the length of a string without including
= '\0'; the null-terminator character at the end
11 of a string.
12 str_len = strlen(lab_name);
13 printf("String length: %d\n",
str_len);
14 return 0;
15 }

Existence of a Character in a String

Program Code Input and Output


1 #include <stdio.h> === Input ===
2 #include <string.h> Free type (~50 letters):
3 Tel-u students are very
4 int main(void) { ambitious!
5 char string[50 + 1], character;
6 Insert single character: U
7 printf("Free type (~50 letters): ");
8 fgets(string, 50, stdin); === Output ===
9 string[strlen(string) - 1] = '\0'; Not found...
10
11 printf("Insert single character: "); === Explanation ===
12 scanf("%c", &character); Note that even though we
13 know there is a letter 'U'
14 if (strchr(string, character) != NULL) { in the string, 'U' is not
15 printf("Found character '%c'!\n"); the same as the character
16 } else { 'u' that we want to search
17 printf("Not found...\n"); for. This is because the
18 } strchr() function is very
19 // Try to experiment based on the given case-sensitive, where the
20 // problem and solution on the right side capitalization of a single
21 // of this specific table. The solution letter is very important.
22 // can be made by yourself based on your The solution to this problem
23 // understanding behind the logic is to try changing the
individually entire string to upper or
24 // by searching the solutions on the lower case, then the
internet strchr() process is carried
25 // and try to re-implement them back... out.
26 return 0;
27 }

Algorithm and Programming Practicum Module 2024/2025


59
Existence of a Substring in a String

Program Code Input and Output


1 #include <stdio.h> === Input ===
2 #include <string.h> Insert the main string (~50):
3 Tel-U students are very
4 int main(void) { ambitious!
5 char string[50 + 1], substring[50 + 1];
6 Insert a substring (~50):
7 printf("Insert the main string (~50): "); aMBiSiUs
8 fgets(string, 50, stdin);
9 string[strlen(string) - 1] = '\0'; === Output ===
10 Not found...
11 printf("Insert a substring (~50): ");
12 fgets(substring, 50, stdin); === Explanation ===
13 substring[strlen(substring) - 1] = '\0'; As with the strchr() problem,
14 case-sensitivity also applies
15 if (strstr(string, substring) != NULL) { to the strstr() function, that
16 printf("Found the substring!\n"); even though according to humans
17 } else { it "exists" even though it is
18 printf("Not found...\n"); written differently, it is not
19 } so for computers. The
20 // Try to experiment based on the given appropriate solution is also to
21 // problem and solution on the right side capitalize or reduce the main
22 // of this specific table. The solution string unit with the sub-
23 // can be made by yourself based on your string, then search for the
24 // understanding behind the logic equality of the two strings
individually with the strstr() method.
25 // by searching the solutions on the
internet
26 // and try to re-implement them back...
27 return 0;
28 }

Introductory of NULL and size_t Data Type

Program Code Output


1 #include <stdio.h> === Output ===
2 #include <string.h> 6969696969696969
3 Before: (null)
4 int main(void) { After: Hewlett-Packard Company
5 char *company_name = NULL;
6 size_t some_number = === Explanation ===
6969696969696969LL; A short example of how to use NULL
7 and size_t in C programming.
8 printf("%zu\n", some_number);
9 printf("Before: %s\n", company_name);
10
11 company_name = "Hewlett-Packard
Company";

Algorithm and Programming Practicum Module 2024/2025


60
12 printf("After: %s\n", company_name);
13 return 0;
14 }

Method 4: Manipulate (Customize) Errors with Strings


Standard headerrequired files and functions: <errno.h>; strerror()

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>.

Program Code Input and Output


1 #include <stdio.h> === Output ===
2 #include <string.h> FAIL: No such file or directory
3 #include <errno.h>
4 === Explanation ===
5 int main(void) { In short, this program wants to
6 FILE *my_file = fopen("a.txt", "r"); open a file named “a.txt” with the
7 “r” (read) method. However, because
8 if (my_file == NULL) { the file has not been created
9 printf("FAIL: %s\n", before, the my_file variable
strerror(errno)); automatically has a NULL value
10 } else { because it cannot be opened (a null
11 printf("File is successfully file). The output obtained is a
opened!\n"); message that the file or directory
12 } does not exist in the user's
13 storage (according to the original
14 // Once again, this is just for an translation).
example
15 // for how to use strerror() properly.
16 // The following more use-cases of
strerror()
17 // can be independently taught
individually
18 // by searching over the course of all
19 // the internet...
20 return 0;
21 }

Algorithm and Programming Practicum Module 2024/2025


61
Sample Program and Flowchart: Username-based Password Generator
Program Code
1 #include <stdio.h>
2 #include <string.h>
3
4 int main(void) {
5 char username[20 + 1], password[(20 * 2) + 1];
6 char last_password[(20 * 2) + 1];
7 char find_char, find_substring[20 + 1];
8
9 printf("Insert any username: ");
10 fgets(username, 20, stdin);
11 username[strlen(username) - 1] = '\0';
12
13 strcpy(password, username); strcat(password, "2024");
14
15 printf("Insert a character: ");
16 scanf("%c", &find_char);
17
18 fflush(stdin);// Clean the input buffer after using scanf().
19 printf("Insert a substring: "); fgets(find_substring, 20, stdin);
20 find_substring[strlen(find_substring) - 1] = '\0';
21
22 puts("");
23 if (strchr(password, find_char) != NULL && strstr(password, find_substring)
!= NULL) {
24 printf("Both characters and substrings are PRESENT in the password!\n");
25 } else {
26 printf("One of them or both are NOT PRESENT in the password...\n");
27 }
28
29 puts("");
30 printf("Insert the final password: "); fgets(last_password, 40, stdin);
31 last_password[strlen(last_password) - 1] = '\0';
32
33 if (strcmp(password, last_password) == 0) {
34 printf("CORRECT password! Thanks for playing...\n");
35 } else {
36 printf("INCORRECT password, better luck next time...\n");
37 }
38
39 return 0;
40 }
=== INPUT AND OUTPUT ===
Insert any username: 10102230ABCD
Insert a character: A
Insert a substring: 30AB
Both character and substring are PRESENT in the password!
Insert the final password: 10102230ABCD2024
CORRECT passwords! Thanks for playing...
Flow chart

Algorithm and Programming Practicum Module 2024/2025


62
Algorithm and Programming Practicum Module 2024/2025
63
MODULE 7 : SORTING

Objectives of the Practicum


1. Understand and comprehend the logic of sorting using the selection,
insertion, and bubble methods.
2. Able to implement sorting logic into a program using C language.

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:

7.1 Selection Sort


The working principle of selection sort is:
a. Find the extreme value (maximum or minimum) in array A (let's say array A is the array
to be sorted) and swap the 2nd index with the first index.
b. Then determine the next extreme value and exchange it with the second index, then
isolate the second index.
c. Repeat these steps until the last data.

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

A[0] A[1] A[2] A[3] A[4] A[5]

• Step 1

1 2 3 7 4 3

A[0] A[1] A[2] A[3] A[4] A[5]

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

A[0] A[1] A[2] A[3] A[4] A[5]

Algorithm and Programming Practicum Module 2024/2025


64
Find the minimum data contained in the Array (Index 1-5) then swap it with the data at the
1st index then isolate. It is found that the minimum value in the Array (Index 1-5) is the number
2 (1st Index), because the number is already in the 1st Index so it does not swap places then
isolate.

• Step 3

1 2 3 7 4 3

A[0] A[1] A[2] A[3] A[4] A[5]

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

A[0] A[1] A[2] A[3] A[4] A[5]

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

A[0] A[1] A[2] A[3] A[4] A[5]

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

A[0] A[1] A[2] A[3] A[4] A[5]

The data is sorted in ascending order.

Algorithm and Programming Practicum Module 2024/2025


65
C Input and Output
1 #include <stdio.h> INPUT EXAMPLE
2 int a[100]; Number of data: 6
3 int i, j, n, min, temp; Data 1: 3
4 Data 2: 2
5 int main() Data 3: 1
6 { Data 4: 7
7 printf("Number of data: "); Data 5: 4
8 scanf("%d", &n); Data 6: 3
9 for (i = 0; i <= n - 1; i++){
10 printf("Data %d: ", i + 1); OUTPUT
11 scanf("%d", &a[i]); 1 2 3 3 4 7
12 }
13
14 // selection sort process
15 for (i = 0; i <= n - 2; i++){
16 min = i;
17 for (j = i; j <= n - 1; j++){
18 if (a[j] < a[min]){
19 min = j;
20 temp = a[min];
21 a[min] = a[i];
22 a[i] = temp;
23 }
24 }
25 }
26
27 // display the sorting results
28 for (i = 0; i <= n - 1; i++){
29 printf("%d", a[i]);
30 printf(" ");
31 }
32 }

Algorithm and Programming Practicum Module 2024/2025


66
Flow chart

Algorithm and Programming Practicum Module 2024/2025


67
7.2 Insertion Sort
The working principle of insertion sort is to sort the numbers that have been read and then
repeatedly compare and insert the numbers that have been read to the left side of the array if
the data in the previous array index has not been sorted. The sorting process starts from the
second index. The following is an example of ascending sorting using insertion sort:
Array A

3 2 1 7 4 3

A[0] A[1] A[2] A[3] A[4] A[5]

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:

a. Take the second data from array A, namely A[1]

3 1 7 4 3

A[0] A[1] A[2] A[3] A[4] A[5]

b. Swap and insert data in the grey section

2 3 1 7 4 3

A[0] A[1] A[2] A[3] A[4] A[5]

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

A[0] A[1] A[2] A[3] A[4] A[5]

d. Repeat the process until the end

1 2 3 7 4 3

A[0] A[1] A[2] A[3] A[4] A[5]

Algorithm and Programming Practicum Module 2024/2025


68
1 2 3 4 7 3

A[0] A[1] A[2] A[3] A[4] A[5]

1 2 3 3 4 7

A[0] A[1] A[2] A[3] A[4] A[5]

C Input and Output


1 #include <stdio.h> INPUT EXAMPLE
2 int a[100]; Number of data: 6
3 int i, j, n, temp; Data 1: 3
4 Data 2: 2
5 int main(){ Data 3: 1
6 printf("Number of data: "); Data 4: 7
7 scanf("%d", &n); Data 5: 4
8 for (i = 0; i <= n - 1; i++){ Data 6: 3
9 printf("Data %d: ", i + 1);
10 scanf("%d", &a[i]); OUTPUT
11 } 1 2 3 3 4 7
12
13 // insertion sort process
14 for (i = 0; i <= n - 1; i++){
15 temp = a[i];
16 j = i;
17 while ((j > 0) && (temp < a[j - 1])){
18 a[j] = a[j - 1];
19 j = j - 1;
20 }
21 a[j] = temp;
22 }
23
24 // display the sorting results
25 for (i = 0; i <= n - 1; i++){
26 printf("%d", a[i]);
27 printf(" ");
28 }
29 }

Algorithm and Programming Practicum Module 2024/2025


69
Flow chart

Algorithm and Programming Practicum Module 2024/2025


70
7.3 Bubble Sort
The working principle of bubble sort is to compare data (data i) with the data next to it (data
i+1), the data will be exchanged if the data is larger than the data next to it (ascending
sorting).
Here is an example of sorting for ascending (order from smallest to largest) using the bubble
sort method:

Array A

3 2 1 7 4 3

A[0] A[1] A[2] A[3] A[4] A[5]

• Step 1

2 3 1 7 4 3

A[0] A[1] A[2] A[3] A[4] A[5]

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

A[0] A[1] A[2] A[3] A[4] A[5]

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

A[0] A[1] A[2] A[3] A[4] A[5]

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

A[0] A[1] A[2] A[3] A[4] A[5]

Algorithm and Programming Practicum Module 2024/2025


71
2 1 3 4 3 7

A[0] A[1] A[2] A[3] A[4] A[5]

1 2 3 4 3 7

A[0] A[1] A[2] A[3] A[4] A[5]

1 2 3 4 3 7

A[0] A[1] A[2] A[3] A[4] A[5]

1 2 3 4 3 7

A[0] A[1] A[2] A[3] A[4] A[5]

1 2 3 3 4 7

A[0] A[1] A[2] A[3] A[4] A[5]

C Input and Output


1 #include <stdio.h> INPUT EXAMPLE
2 int a[100]; Number of data: 6
3 int i, j, n, temp; Data 1: 3
4 int main(){ Data 2: 2
5 printf("Number of data: "); Data 3: 1
6 scanf("%d", &n); Data 4: 7
7 for (i=0;i<=n-1;i++){ Data 5: 4
8 printf("Data %d: ", i + 1); Data 6: 3
9 scanf("%d", &a[i]);
10 } OUTPUT
11 // bubble sort process 1 2 3 3 4 7
12 for (i = n - 1; i >= 1; i--){
13 for (j = 1; j <= i; j++){
14 if (a[j - 1] > a[j]){
15 temp = a[j - 1];
16 a[j - 1] = a[j];
17 a[j] = temp;
18 }
19 }
20 }
21 // display the sorting results
22 for (i = 0; i <= n - 1; i++){
23 printf("%d", a[i]);
24 printf(" ");
25 }
26 }

Algorithm and Programming Practicum Module 2024/2025


72
Flow chart

Algorithm and Programming Practicum Module 2024/2025


73
MODULE 8 : SEARCHING

Objectives of the Practicum


1. Understand and comprehend search logic using sequential and binary
methods.
2. Able to implement search logic into a program using C language.

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.

8.1 Sequential Search


Sequential search is the simplest search method, where the search is done sequentially from
the first data until the data being searched for is found. Data is compared one by one from the
beginning until the data is found or not found. Sequential search is usually used when the available
data set is not sorted, used on small data sets, or data sets that are not often searched.
In sequential search, let's say there is an array with lots of data in it, we start the search
process at the starting index of the array and will continue until we find the value we are looking for,
or the ending index of the array (or the data is not found). Here is an example of a search using
sequential search:

Suppose there is an array A with size 7.

4 21 36 14 62 92 6

A[0] A[1] A[2] A[3] A[4] A[5] A[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

A[0] A[1] A[2] A[3] A[4] A[5] A[6]

Algorithm and Programming Practicum Module 2024/2025


74
Index
21 is not the same as 14
1

4 21 36 14 62 92 6

A[0] A[1] A[2] A[3] A[4] A[5] A[6]

Index
36 is not equal to 14
2

4 21 36 14 62 92 6

A[0] A[1] A[2] A[3] A[4] A[5] A[6]

14 is the same as 14, so the


Index data is found at index 3

4 21 36 14 62 92 6

A[0] A[1] A[2] A[3] A[4] A[5] A[6]

Here is an example flowchart and C code for the above example:


C Input and Output
1 #include <stdio.h> EXAMPLE 1:
2 Data to be searched:
3 int A[7] = {4, 21, 36, 14, 62, 92, 6}; 14
4 int search, idx, dataAmount;
5 OUTPUT
6 void main(){ Data found at index:
7 // User enters the data to be searched 3
8 printf("Data to be searched: ");
9 scanf("%d", &search); EXAMPLE 2:
10 Data to be searched:
11 // Sequential search process 5
12 idx = 0;// Position searching at index 0
13 dataAmount = 7;// Size of array A OUTPUT
14 while((idx < dataAmount) && (A[idx] != search)){ Data not found

Algorithm and Programming Practicum Module 2024/2025


75
15 idx++;// If the index is not data searching for,
16 // then it will continue to the next index.
17 }
18 if(A[idx] == search){
19 printf("\nData found at index: %d", idx);
20 } else {
21 printf("\nData not found");
22 }
23 }

Flow chart

Algorithm and Programming Practicum Module 2024/2025


76
8.2 Binary Search
The sequential search algorithm is a slow algorithm when the data to be searched is in a
large data set. So we use a more efficient algorithm, namely binary search. Before using this
algorithm, the data needs to be sorted first.

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).

Here is an example of a search using binary search:


Suppose there is an array B with size 12.
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]

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]

Low Mid High


8 < 10
0 2 4

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]

Algorithm and Programming Practicum Module 2024/2025


77
Low Mid High
10 = 10
3 3 4

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]

Here is an example flowchart and C code for the above example:


C Input and Output
1 #include <stdio.h> EXAMPLE 1:
2 int B[12] = {4, 7, 8, 10, 14, 21, INPUT
3 22, 36, 62, 77, 81, 91}; Data to be searched: 10
4 int search, idx, low, high, mid;
5 void main(){
OUTPUT
6 // User inputs the target data
7 printf("Data to be searched: "); Data found at index: 3
8 scanf("%d", &search);
9
10 // Sorting process
11 /* EXAMPLE 2:
12 Input a sorting algorithm here INPUT
13 (bubble, insertion, etc.) Data to be searched: 3
14 */
15
OUTPUT
16 // Binary search process
17 low = 0; Data not found
18 high = 12 - 1;// 12 because the size of the array is
12
19 idx = -1;
20 while((low <= high) && (idx == -1)){
21 mid = (low+high)/2;
22 if(B[mid] == search){
23 idx = mid;
24 } else if (B[mid] < search){
25 low = mid + 1;
26 } else {
27 high = mid - 1;
28 }
29 }
30 if(idx != -1){
31 printf("\nData is found at index: %d", idx);
32 } else {
33 printf("\nData is not found");
34 }
35 }

Algorithm and Programming Practicum Module 2024/2025


78
Flow chart

Algorithm and Programming Practicum Module 2024/2025


79
MODULE 9 : POINTER

Objectives of the Practicum


1. Understanding the concept of pointers and arrays.
2. Master pointer operations.
3. Able to define and initialize pointers.
4. Using pointers in programs.
5. Understanding the relationship between pointers and arrays, pointers and strings,
and pointers and structs.
6. Implementing the concepts of pointers and arrays, pointers and strings, and
pointers and structs.

9.1 Understanding Pointer


Each variable will have a memory address that functions to determine the location of data
storage in memory (RAM). Memory addresses are sometimes called references.

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;

Algorithm and Programming Practicum Module 2024/2025


80
There are also functions of pointers, namely:
1. Stores the address of a variable.
2. Accessing and modifying values from other memory locations. With pointers, we can access
and modify the value of a variable stored at the memory address referenced by the pointer.
Example:
1 int x = 15;
2 int *ptrX = &x;
3 printf(“%d”, *ptrX); // Output = 15
4 *ptrX = 40;
5 printf(“%d”, x); // Output = 40

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

5. Passing parameters by reference. Pointers can be used to pass arguments to functions by


reference, allowing changes to the arguments within the function.
Example:
1 void increment(int *num) {
2 (*num)++;
3 }
4
5 int main() {
6 int x = 10;
7 increment(&x);
8 printf("%d", x); // Output: 11
9 return 0;
10 }

Algorithm and Programming Practicum Module 2024/2025


81
6. Pointers to pointers. Pointers can also point to other pointers, allowing for more complex
data structures.
Example:
1 int x = 10;
2 int *ptr = &x;
3 int **ptr2 = &ptr;
4 printf("%d", **ptr2); // Output: 10

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;”.

Algorithm and Programming Practicum Module 2024/2025


82
9.2 Pointer Operators
In pointers, there are several operators that can be used, namely:
a. The address-of operator, symbolized by the symbol "&", functions to get the address of a
variable.
int tult = 10;
int *ruang_daskom = &tult; // address operator
printf("Tult variable address: %x\n", room_daskom);
// output: 0x6a2F242c example tult variable address
b. The dereference operator, symbolized by the symbol "*", is an operator to get the contents
of a pointer value.
int tult;
int *room_daskom = &tult;
*space_daskom = 10 // *y = contents of address x

Example of use in the program:


Program Code Program Output

1 #include <stdio.h> Tult address:


2 int main() { 0x0000009b3b3ff814
3 int tult = 10;
Tult value before
4 // declare variable tult with value 10
dereference: 10
5
6 int *daskom_location; Tult value after
7 // declaration of daskom_location pointer dereference: 1001
8
9 // Address-of operator (&)
10 daskom_location = &tult;
*address may vary
11 // ruang_daskom points to the address of the variable
tult
12
13 printf("Tult address: %p\n", daskom_location);
14 // display the address of the text
15
16 // Dereference operator (*)
17 printf("Tult value before dereference: %d\n", tult);
18
19 * daskom_location = 1001;
20 // change the value of the variable pointed to by
daskom_location
21 printf("Tult value after dereference: %d\n", tult);
22 return 0;
23 }

Algorithm and Programming Practicum Module 2024/2025


83
9.3 Void Pointer
A void pointer is a type of pointer that can store the address of a variable with any data
type. Unlike pointers that have a specific type, such as int* or char*, a void pointer does not have
a specific data type, therefore it is called a general or universal pointer. This pointer is very useful in
situations where the data type of the address to be stored is unknown or can vary.
Examples of its use include memory functions such as scanf and various functions that take
generic pointers as arguments or return values. To access or manipulate the data pointed to by a
void pointer, an explicit casting to the appropriate data type is required.
Example of use in the program:

Program Code Program Output

1 #include <stdio.h> daskom_location via void


2 pointer: 1004
3 int main() {
mineral_price via void
4 int daskom_location = 1004;
pointer: 2000.99
5 float mineral_price = 2000.99;
6 char score = 'A'; score via void pointer: A
7
8 // Declare a void pointer
9 void *ptr;
10
11 // Points to a variable of type int
12 ptr = &daskom_location;
13 printf("daskom_location via void pointer:
%d\n", *(int*)ptr);
14 // Points to a variable of type float
15 ptr = &mineral_price;
16 printf("mineral_price via void pointer:
%.2f\n", *(float*)ptr);
17 // Points to a variable of type char
18 ptr = &score;
19 printf("score via void pointer: %c\n",
*(char*)ptr);
20 return 0;
21 }

9.4 Pointer and Array


An array is a collection of similar elements stored in contiguous memory locations. A regular
variable can only store one value at a time. However, there are situations where we want to store
more than one value at a time in a single variable. For example, we want to store percentage values
in memory. In this case, we have two options for storing these values:
(a) Create 100 variables to store the percentage scores obtained by 100 different students; that
is, each variable contains the score of one student.
(b) Create one variable (called a subscripted variable) that is able to store or accommodate all
the scores of the one hundred students.

Algorithm and Programming Practicum Module 2024/2025


84
In C, pointers and arrays have a close and interrelated relationship. An array name is essentially a
pointer to the first element of the array, allowing access to array elements using pointer notation,
where *(arr + i) is equivalent to arr[i].

General Form of Array:


type array_name[size];

Example of Accessing array using Pointer:


Program Code

1 #include <stdio.h>

2 int main() {

3 int score[5] = {70, 80, 90, 95, 100};

4 int *ptr = score;// ptr points to the address of the first element of arr

5 // array address

6 printf("Array address: %p\n", (void*)ptr);

7
8 // array values can be accessed with pointers

9 printf("Practitioner 1's score: %d\n", *ptr);

10 printf("Practitioner 2's score: %d\n", *(ptr + 1));

11

12 // using loop to access array values

13 // array index nodes start from 0

14 printf("Student’s score using loop:\n");

15 for (int i = 0; i < 5; i++) {

16 printf("Score %d: %d\n", i + 1, *(ptr + i));

17 }

18 return 0;

19 }

Example of Changing Array Values using Pointers:

Program Code Program Output

1 #include <stdio.h> numbers[0] = 10,


2 *(p + 0) = 10
3 int main() {
numbers[1] = 20,
4 int num[5] = {10, 20, 30, 40, 50};
*(p + 1) = 20
5 int *my_pointer;
6
7 // Pointer points to the beginning of the array

Algorithm and Programming Practicum Module 2024/2025


85
8 my_pointer = num; numbers[2] = 30,
9 *(p + 2) = 30
10 // Access array elements via pointer
numbers[3] = 40,
11 for (int i = 0; i < 5; i++) {
*(p + 3) = 40
12 printf("numbers[%d] = %d, *(p + %d) = %d\n", i,
num[i], i, *(my_pointer + i)); numbers[4] = 50,
13 } *(p + 4) = 50
14
15 // Change the value of an array element through a After changing
pointer the value:
16 *(my_pointer + 2) = 100;// Change the 3rd element(index
numbers[0] = 10
2) becomes 100
17 printf("After changing the value:\n"); numbers[1] = 20
18 for (int i = 0; i < 5; i++) {
numbers[2] = 100
19 printf("numbers[%d] = %d\n", i, num[i]);
20 } numbers[3] = 40
21
22 return 0; numbers[4] = 50
23 }

9.5 Arithmetic Operations On Pointer


Pointers can act as operands in arithmetic operations. This kind of process is often called
pointer arithmetic. It is usually used as an alternative notation for arrays but using pointers. A pointer
variable can only perform arithmetic operations with integer values. There are only two arithmetic
operations that can be applied to pointers, namely addition and subtraction. Here are examples of
arithmetic operations on pointers:

Program Code Program Output

1 #include <stdio.h> After incrementing the


2 pointer:
3 int main() {
Address: 00000070db5ffd44,
4 int number[] = {10, 20, 30, 40, 50};
Value: 20
5 int *ptr = number;
6 // Points to the first element of the array After decrementing the
7 pointer:
8 // Add pointer
9 ptr++; Address: 00000070db5ffd40,
10 // Pointer moves to next element Value: 10
11 printf("After incrementing the pointer:\n");
After adding 3 to the
12 printf("Address: %p, Value: %d\n", ptr, *ptr);
pointer:
13
14 // Pointer decrement Address: 00000070db5ffd4c,
15 ptr--; Value: 40
16 // Pointer back to previous element
After subtracting 2 from
17 printf("After decrementing the pointer:\n");
pointer:
18 printf("Address: %p, Value: %d\n", ptr, *ptr);
19 // Add an integer to a pointer Address: 00000070db5ffd44,
20 ptr += 3; Value: 20
21 // Pointer moves 3 elements forward
22 printf("After adding 3 to the pointer:\n");

Algorithm and Programming Practicum Module 2024/2025


86
23 printf("Address: %p, Value: %d\n", ptr, *ptr);
24
25 // Integer subtraction from pointer
26 ptr -= 2;
27 // Pointer moves 2 elements back
28 printf("After subtracting 2 from pointer:\n");
29 printf("Address: %p, Value: %d\n", ptr, *ptr);
30
31 return 0;
32 }

9.6 Pointer and String


A string in C is essentially an array of characters terminated by a null character ('\0'), and
can be represented as a pointer to its first character. A char pointer can be used to point to the
beginning of a string, allowing access and manipulation of individual characters in the string. When
declaring a string as a character array, the array name serves as a constant pointer to the first
element, while pointers to char provide more flexibility in string operations, including iterating
through characters, modifying the string, and passing the string to functions.

Example:

char *str = “Algorithm”;

Example of use in the program:

Program Code Program Output

1 #include <stdio.h> Original string:


2 int main() { Algorithm
3 // Declare and initialize a pointer to a string
String after
4 char *str = "Algorithm";
pointer is shifted:
5
arithm
6 // Print the string pointed to by the pointer
7 printf("Original string: %s\n", str);
8
9 // Shift the pointer by 3 positions
10 str += 3;
11
12 // Print the string pointed to by the pointer after
the shift.
13 printf("String after pointer is shifted: %s\n", str);
14 return 0;
15 }

Algorithm and Programming Practicum Module 2024/2025


87
9.7 Pointer As Function Parameters
Pointers can be used as function parameters. This allows the function to directly access and
modify data at the memory address pointed to by the pointer.

Example of use in the program:

Program Code Program Output

1 #include <stdio.h> Value before


2 exchange:
3 // Function to swap the values of two variables
x = 5, y = 10
4 void swap(int *a, int *b) {
5 int temp; Value after
6 temp = *a; exchange:
7 // Store the value of a in temp
8 *a = *b; x = 10, y = 5
9 // Copy the value of b to a
10 *b = temp;
11 // Copy the temp value (initial value of a) to b
12 }
13
14 int main() {
15 int x = 5;
16 int y = 10;
17
18 printf("Value before exchange:\n");
19 printf("x = %d, y = %d\n", x, y);
20
21 // Call the exchange function and pass the addresses of
x and y
22 swap(&x, &y);
23
24 printf("Value after exchange:\n");
25 printf("x = %d, y = %d\n", x, y);
26
27 return 0;
28 }

9.8 Pointers with Structs


Struct is a way to group data that has different data types into one unit. Struct is defined using the
struct keyword.

Struct Example:

struct student {
char name[50];
int nim;
float value;
} student_data;

Algorithm and Programming Practicum Module 2024/2025


88
Array of struct is a way to store a collection of struct data with the same data type.

Example:

struct student {
char name[50];
int nim;
float value;
} data_mahasiswa[30]; //example of using array in struct

Nested struct is a way to define a struct within another struct.

Example of use in the program:

Program Code Program Output


1 #include <stdio.h> // == INPUT IN THE
2 // Address struct definition PROGRAM ==
3 struct address {
Enter student name:
4 char street[50];
Teguh
5 char city[50];
6 char province[50]; Enter student NIM:
7 }; 1010
8
9 // Definition of student struct with nested address Enter student grades:
struct 100
10 struct student {
Enter street address:
11 char name[50];
dorm
12 int nim;
13 float score; Enter city: bandung
14 struct address home_address;
Enter province: Java
15 };
16
17 int main() {
18 // Declare a variable of type struct student // == OUTPUT IN THE
19 struct student mhs; PROGRAM ==
20 Student Data:
21 // Fill in data for students
22 printf("Enter student name: "); Name: Teguh
23 scanf("%49s", &mhs.name);
NIM: 1010
24 // Read name with 49 character limit
25 printf("Enter student NIM: "); Value: 100.00
26 scanf("%d", &mhs.nim);
27 // Reading NIM
28 printf("Enter student grades: "); Home Address:
29 scanf("%f", &mhs.score);
30 // Read the value Street: dorm
31
City: bandung
32 // Fill in the data for the student's home address
33 printf("Enter street address: "); Province: Java
34 scanf("%49s", mhs.home_address.street);
35 // Read path with 49 character limit

Algorithm and Programming Practicum Module 2024/2025


89
36 printf("Enter city: ");
37 scanf("%49s", mhs.home_address.city);
38 // Read city with 49 character limit
39 printf("Enter province: ");
40 scanf("%49s", mhs.home_address.province);
41 // Read provinces with a limit of 49 characters
42
43 // Displays student data and home address
44 printf("\nStudent Data:\n");
45 printf("Name: %s\n", mhs.name);
46 printf("NIM: %d\n", mhs.nim);
47 printf("Value: %.2f\n", mhs.score);
48 printf("\nHome Address:\n");
49 printf("Street: %s\n", mhs.home_address.street);
50 printf("City: %s\n", mhs.home_address.city);
51 printf("Province: %s\n", mhs.home_address.province);
52 return 0;
53 }

Pointer to struct is a way to store the memory address of a struct.

Example of use in the program:

Program Code Program Output

1 #include <stdio.h> // == INPUT IN THE


2 #include <stdlib.h>// For malloc and free PROGRAM ==
3
Enter student name: Ali
4 // Definition of student struct
5 struct student{ Enter student NIM:
6 char name[50]; 110223244
7 int nim;
8 float grade; Enter student grades:
9 }; 100
10
11 int main() {
// == OUTPUT IN THE
12 // Declare pointer for struct mahasiswa
PROGRAM ==
13 struct student *ptr_mhs;
14 Student Data:
15 // Allocate memory for one student struct
Name: Ali
16 ptr_mhs = (struct student *) malloc(sizeof(struct
student)); NIM: 110223244
17
18 if (ptr_mhs == NULL) { Rating: 100.00
19 printf("Memory allocation failed.\n");
20 return 1;
21 }
22
23 // Insert data into struct via pointer
24 printf("Enter student name: ");
25 scanf("%49s", ptr_mhs->name);
26 // Read name with 49 character limit

Algorithm and Programming Practicum Module 2024/2025


90
27 printf("Enter student NIM: ");
28 scanf("%d", &ptr_mhs->nim);// Reading NIM
29 printf("Enter student grades: ");
30 scanf("%f", &ptr_mhs->grade);// Read the value
31
32 // Display the entered data
33 printf("\nStudent Data:\n");
34 printf("Name: %s\n", ptr_mhs->name);
35 printf("NIM: %d\n", ptr_mhs->nim);
36 printf("Value: %.2f\n", ptr_mhs->grade);
37
38 // Free allocated memory
39 free(ptr_mhs);
40
41 return 0;
42 }

9.9 Malloc and Free Functions


The malloc and free functions are two very important functions in the C programming language
(and other languages that use the concept of manual memory allocation). Here is a brief explanation
of both:

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.

Algorithm and Programming Practicum Module 2024/2025


91
MODULE 10 : FILE INPUT/OUTPUT

Objectives of the Practicum


1. Understand file shapes in the algorithm.
2. Understanding data storage using text files and binary files.
3. Can differentiate between text files and binary files.
4. Can open files, close files, write data to files, and read them for both text and
binary files in algorithms and in C language.

10.1 Understanding Input/Output Files


Input/output files are used so that the results of an executed program can be stored
permanently in any storage device, rather than temporarily disappearing when the program is
closed or stopped. The goal is that the data that has been stored can be reused.
The C language provides a structure that can be used to store all the information needed to
control the data flow of a file, namely the FILE structure (often also called a file handle) and is
declared in the standard header file stdio.h. This structure will store information about the flow of a
file including a file position indicator, a buffer pointer (if any), an error indicator that stores when a
read/write error occurs, an end-of-file indicator that stores when the end of a file has been reached,
and other information needed.
The first way to get information from the FILE structure is to declare a pointer that will point to
the FILE structure. This kind of pointer is called a file pointer. The following is the general form of
declaring a pointer to the file referred to above:

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

Algorithm and Programming Practicum Module 2024/2025


92
10.2 Opening Files
Before a file can be processed (read or written), the file must be opened first. For this purpose,
there is a function called fopen. Here is the basic form:

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.

For example, here is an example of using the fopen function:

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.

Algorithm and Programming Practicum Module 2024/2025


93
❖ The writing process should not be immediately followed by a writing process without an
intervention call to the fflush function or a file positioning function (fseek, fsetpos, or rewind),
unless the reading process has reached the end of a file (end-of-file).
* The fflush, fseek, fsetpos and rewind functions will be discussed later in this module.

10.3 Processing Files


When a file is opened, it can be treated as a binary file or a text file. A binary file is a file whose
data is processed in the form of memory blocks consisting of bytes, such as memory in RAM.
Meanwhile, a text file is a file whose data will be processed in the form of characters.
A text file is usually used to store character or string type data. Meanwhile, binary files are usually
used to store complex data, such as structures (structs).
What can be done to work with binary files is to add an additional character, namely "b" to the
mode argument of the fopen function. Meanwhile, to work with text files, no characters need to be
added to them.

• 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.

int fprintf(FILE * restrict stream, const char * restrict format, ...);

char *fgets(char * restrict s, int n, FILE * restrict stream);


Description :
❖ s is string data.
❖ stream is a FILE pointer.
❖ n defines how many characters to store in the string s.
❖ The fprintf function is used to write a string s into a file based on the string indicated by the
format to determine the arguments (…) which will then be converted into output on the file. This
function will return the number of characters written, or a negative value if the output or error
of the character encoding process on the file occurs.
❖ The fgets function is used to read a string from a file into a string s. If the end of the file has
been reached then s will remain unchanged and the function will return a NULL value. However,
if an error occurs, the contents of the string s cannot be determined and the function will return
a NULL value. If successful then it will return the string s.

Algorithm and Programming Practicum Module 2024/2025


94
Writing String Data to
Flow chart
in Text File
#include <stdio.h>

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;
}

Reading String Data Flow chart


from Text File
#include <stdio.h>

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;
}

Algorithm and Programming Practicum Module 2024/2025


95
Note that the format argument used in the fprintf function, "%s\n", has a newline character
in it. This newline character must be manually written into the file, without it, instead of creating a
text file that consists of more than one line properly, the file will be written in just one line.
In addition to using the fgets function, fgetc can also be used to read string data. The
difference is that fgets is used to read in a string basis, while fgetc is used to read in a character
basis (remember that a string is a collection of characters, in other words an array of char). Here is
the basic form.

int fgetc(FILE *stream);

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");

while ((ch = fgetc(f_teks)) != EOF) {


putchar(ch);
}

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.

Algorithm and Programming Practicum Module 2024/2025


96
2. Adding Data to a Text File
The method for adding data to a file is almost the same as the method for writing data. The
difference lies in the filemode argument in the fopen function that is being opened by the file. It's
simple, change the filemode "w" or "w+" to "a" or "a+" to add.
Adding String Data Flow chart
into Text File
#include <stdio.h>

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).

Algorithm and Programming Practicum Module 2024/2025


97
❖ size is the size of a block of memory in bytes to be read or written.
❖ nmemb is the number of memory blocks that will be read or written at one time.
❖ stream is a file pointer that points to FILE.
❖ size_t, is a special integer data type that can store the size of an object (such as variables,
arrays, data types and anything that can store values) stored in memory in bytes. This
data type is also the sizeof operator.
❖ Both functions return the number of memory blocks successfully read (for fread) or
written (for fwrite) at a time.
❖ To be able to write or read data from more than one block of memory (based on the
value of nmemb), an array must be used as temporary storage as input to the ptr
argument.

Writing Data into a Binary File


#include <stdio.h>

int main(){
FILE *f_biner;
int n, i;
struct {
char nama[10], nim[10];
int nilai;
} data;

f_biner = fopen("data_mhs.dat", "wb");

printf("Banyaknya Mhs: ");


scanf("%d", &n); getchar();
for(i=1; i<=n; i++){
printf("Nama : ");
gets(data.nama);
printf("NIM: ");
gets(data.nim);
printf("Nilai: ");
scanf("%d", &data.nilai);
getchar();
fwrite(&data, sizeof(data), 1, f_biner);
}
fclose(f_biner);
return 0;
}

Algorithm and Programming Practicum Module 2024/2025


98
Flow chart

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;
}

Algorithm and Programming Practicum Module 2024/2025


99
Flow chart

2. Adding Data to Binary Files


The method for adding data to a binary file is almost the same as the method for writing data.
Of course, use the filemode “wb”, “wb+”, or “w+b” for writing and “ab”, “ab+”, or “a+b” for
appending.
Adding Data to a Binary File
#include <stdio.h>
int main(){
FILE *f_biner;
int n, i;

struct {
char nama[10], nim[10];
int nilai;
}data;

f_biner = fopen("data_mhs.dat", "ab");


printf("Silahkan masukkan banyaknya mahasiswa : ");
scanf("%d", &n);
getchar();
for (i=1; i<=n; i++){
printf("Nama : ");
gets(data.nama);
printf("NIM : ");
gets(data.nim);
printf("Nilai : ");
scanf("%d", &data.nilai); getchar();
fwrite(&data, sizeof (data), 1, f_biner);
}
fclose(f_biner);
return 0;
}

Algorithm and Programming Practicum Module 2024/2025


100
Flow chart

3. Accessing Binary Files Randomly


C language provides a facility that allows to read and write files randomly by changing the file
position indicator. With this facility, for example, if a data in the middle of the file is to be read, the
data can be read directly without having to be accessed one by one starting from the beginning of
the file.
For this purpose, there is a function called fseek. Here's the basic form:

int fseek(FILE *stream, long int offset, int whence);

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)

Algorithm and Programming Practicum Module 2024/2025


101
. ere is a table of whence references:
H
Macro File Location Reference
SEEK_SET Beginning of file
SEEK_CUR Current file position indicator
SEEK_END End of file
MacThe ro-macro is defined based on a platform's implementation which is an integer constant with different
values.
As an example :
fseek(fp, 3, SEEK_SET); The file position indicator will be changed 3 bytes
after
beginning of the file.
fseek(fp, -3, SEEK_END); The file position indicator will be changed 3 bytes
pay attention to the negative sign. before
end of file.
fseek(fp, 3, SEEK_CUR); The file position indicator will be changed 3 bytes
after
current file position indicator.
fseek(fp, -sizeof(DATA), SEEK_CUR); The file position indicator will be changed based on
pay attention to the negative sign. the size of the DATA object before the indicator.
current file position.

It should be noted that the offset argument can also accept negative values. Extra, the rewind function

void rewind(FILE *stream);

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.

The following is an example of using the fseek function:


Accessing Binary Files Randomly
#include <stdio.h>

int main(){
FILE *f_biner;
int no_struct;
long int offset_byte;

struct {
char nama[10], nim[10];
int nilai;
}data;

f_biner = fopen("data_mhs.dat", "rb");


Algorithm and Programming Practicum Module 2024/2025
102
printf("Silahkan masukkan nomor urutan yang ada pada
data mahasiswa: ");
scanf("%d", &no_struct);
Indikator file posisi akan
offset_byte = (no_struct - 1) * sizeof(data);
diposisikan tepat sebelum
fseek(f_biner, offset_byte, SEEK_SET);
data yang nanti akan
ditampilkan pada layar.
if (fread(&data,sizeof(data),1,f_biner) == 0){
printf("Menu yang dicari tidak dapat ditemukan pada data.\n");
} else {
printf("Nama : %s\n", data.nama);
printf("NIM : %s\n", data.nim);
printf("Nilai : %d\n", data.nilai);
}
fclose(f_biner);
return 0;
}

Flow chart

Algorithm and Programming Practicum Module 2024/2025


103
For example, assume that there are five integer data in a binary file.
7 8 9 10 8

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.

4. Deleting Data in Binary Files


To properly delete data, there are several ways to do it. But there is only one that will be
explained in this module. Here is the correct procedure to do it:
1. Open the main file in read mode.
2. Create a backup file and open it in write mode.
3. Copy all data from the main file into the backup file, except the data to be deleted.
4. Close the main file and backup file.
5. Delete the main file.
6. Change the filename of the backup file based on the filename of the primary file.

C language also provides functions to delete and rename a file, respectively with the
names remove and rename. Here is the basic form:

int remove(const char *filename);

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.

int rename(const char *old, const char *new);

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

Algorithm and Programming Practicum Module 2024/2025


105
5. Update Data in Binary File
To update data correctly, there are several ways to do it. The procedure for updating data on a
binary file is identical to the procedure for deleting data on a binary file. Here is the correct
procedure to do it:
1. Open the main file in read mode.
2. Create a backup file and open it in write mode.
3. Use string compare in the if function to find the matching data, then perform the data update
operation using arithmetic operations then copy it to the backup file.
4. Copy all other data to a backup file.
5. Close the main file and backup file.
6. Delete the main file.
7. Change the filename of the backup file based on the filename of the primary file.

Update Data in Binary File


#include <stdio.h>
#include <string.h>

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;

f_biner = fopen("data_mhs.dat", "rb");


f_biner2 = fopen("data_mhs2.dat", "wb");
printf("Masukkan user yang ingin ditambah poin: ");
gets(user_sekarang);
printf("Masukkan jumlah poin tambahan: ");
scanf("%d", &poin_tambahan);
while (fread(&data, sizeof(data), 1, f_biner) == 1)
{
if (strcmp(data.nama, user_sekarang) == 0)
{
data.poin += poin_tambahan;
poin_baru = data.poin;
temp.poin = poin_baru;
}
fwrite(&data, sizeof(data), 1, f_biner2);
}
fclose(f_biner);
fclose(f_biner2);
remove("data_mhs.dat");
rename("data_mhs2.dat", "data_mhs.dat");
printf("Poin anda sekarang adalah %d", poin_baru);
return 0;
}

Algorithm and Programming Practicum Module 2024/2025


106
Flow chart

10.4 Closing Files


To close a file, there is a function called fclose. Its general form is as follows:

int fclose(FILE *stream);

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.

Algorithm and Programming Practicum Module 2024/2025


107
10.5 Additions
Emptying Buffers on Data Streams

int fflush(FILE *stream);

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.

Writing and Placing file position indicators

int fgetpos(FILE * restrict stream, fpos_t * restrict pos);

int fsetpos(FILE *stream, const fpos_t *pos);

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.

Algorithm and Programming Practicum Module 2024/2025


108
BASIC TECHNICAL REPORT WRITING

Objective

1. Understanding the use of MS Word in making reports


2. Create Automatic Table of Contents, Bibliography, and Captions
3. Can use Formatting Styles
4. Can use Page Numbering with Section break

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).

To adjust the margins, select the Layout menu Margins

Custom Margins→ Set Left-Right-Top-Bottom(4-3-3-3) cm.

Algorithm and Programming Practicum Module 2024/2025


109
2. Multilevel List
Multilevel Listis a hierarchical text numbering
that is arranged automatically, so that lower
level numbering will be increasingly hierarchical.

On the Home menuselect


Paragraph⧫Multilevel
list⧫Heading List

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).

Algorithm and Programming Practicum Module 2024/2025


110
• For heading 1, heading 2, adjust to your needs.
Heading 1 is usually used for Level 1 format
(BIBLIOGRAPHY, TABLE OF CONTENTS, CHAPTER 1) for
heading 2 (level 2 format) is used for Sub-chapters such
as (1.1, 2.2).
• Stylesin Heading 1 & Heading 2, change to Bold,
Times New Roman, size 12, color = black

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).

Algorithm and Programming Practicum Module 2024/2025


112
7. Automatic Table of Contents, Figures, and Tables.
1. To display the Table of Contents automatically, select the Reference menu Table of Contents

Custom table of contents→ Okay.

2. To display the List of Figures and List of Tables, select the Reference menu Table of
Contents Custom table of Contents Ok.

Algorithm and Programming Practicum Module 2024/2025


113
BIBLIOGRAPHY

• Anon., 2019. Functions in the C programmingLanguage.[Online] Available


at:
https://wwow.cs.utah.edu/~germain/PPS/Topics/C_Language/c_functions.
html

• Anon., 2019. Learn C Programming, TheThe Definitive Guide.[Online]


Available at: https://wwow.programiz.com/c-programming

• Gilberg, RF and Forouzan, BA, 2001. Data structures: A pseudocode


approach with C++. Brooks/Cole Publishing Co.

• Gottfried, BS, GarcÃa, L. Ã. and Vaquero, S.Ã., Schaum's outline of theory


and problems of programming with C. spa.

• Kadir, A., 2012. Algorithms & Programming Using C & C++. Yogyakarta:
Andi Offset Publisher.

• Kernighan, BW & Ritchie, DM, 1988. The C Programming Language. Murray


Hill, New Jersey: AT&T Bell Laboratories.

• Perry, GM and Miller, D., 2013. C programming: absolute beginner's guide.


Pearson Education.

• 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

Algorithm and Programming Practicum Module 2024/2025


114

You might also like