JZMH aXKBJ3TwcVIkazQwapfCMfeHvtqxB xBJ1Y

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 84

Laboratorium Dasar Komputer Telkom University

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
Modules can be completed.
On this opportunity, we would like to thank all those who have contributed, so
that the Algorithm and Programming Practicum Module can be published.

We sincerely hope that criticism and suggestions will be improved in the


future. Hopefully, this book can be useful for readers.

Happy reading and practicing.

Bandung, 7 August 2023

Compiler Team

Laboratorium Dasar Komputer Telkom University i


COMPILER LIST
Asistant of Dasar Komputer Laboratory 2023/2024

Laboratorium Dasar Komputer Telkom University ii


LETTER OF STATEMENT

I the undersigned

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

NIP : 14890058

Occupation : Algorithm and Programming Practicum Advisor

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 first
semester of 2021/2022 term at Laboratorium Dasar Komputer, School of Electrical
Engineering, Telkom University.

Bandung, 7 August 2023

Department Head of Electrical Algorithm and Programming Practicum


Engineering Program Advisor

Husneni Mukhtar, S.Si, M.T., Ph.D Dr. Rahmat Awaludin Salam, S.Si., M.Si.

Laboratorium Dasar Komputer Telkom University iii


VISION AND MISSION OF ELECTRICAL ENGINEERING
FACULTY

VISION:
To become a world-class superior faculty that plays an active role in the
development of electrical and physical science and technology, based on information
and communication technology.

MISSION:

1. Organizing higher education and continuing education of international standard.


2. Develop, disseminate, and utilize science and technology in the fields of
telecommunications engineering, computer engineering, physical engineering,
and electrotechnics, as well as in collaboration with industry/institutions, to
improve the welfare and progress of society.
3. Developing and fostering networks with leading universities and industry at home
and abroad in the context of education and research cooperation.
4. Developing resources to achieve excellence in learning, research and community
service.

Laboratorium Dasar Komputer Telkom University iv


VISION AND MISSION OF ELECTRICAL ENGINEERING PROGRAM

VISION :

Become an international standard study program that plays an active role in the development of
education, research, and entrepreneurship and produces graduates in the field of Electronic
Systems, Control Systems, or Embedded Systems.

MISSION :
1. Organizing international standard education to produce graduates who master the
science and technology of Electronic Systems, Control Systems or Embedded
Systems;
2. Develop and disseminate internationally recognized knowledge and technology of
Electronic Systems, Control Systems, and Embedded Systems by actively involving
students;
3. Utilizing the science and technology of Electronic Systems, Control Systems, and
Embedded Systems for the development of entrepreneurship among the academic
community in order to support national economic development.
4. Develop networks with leading universities and industries at home and abroad in
the context of cooperation in education, research, and entrepreneurship in the field
of Electronic Systems, Control Systems, or Embedded Systems,
5. Develop resources to achieve excellence in education, research, and
entrepreneurship in the field of Electronic Systems, Control Systems, or Embedded
Systems.

Laboratorium Dasar Komputer Telkom University v


LABORATORY RULES FOR ELECTRICAL ENGINEERING FACULTY TELKOM
UNIVERSITY

The following are the Rules for the Implementation of Practicum Activities for the Odd
Semester of the 2023/2024 Academic Year.

A. Practicum Rules for Practitioners


Every practitioner who participates in the practicum must comply with the following
rules:
1. All Practitioners MUST wear the official uniform of Telkom University.
2. For safety during the practicum, hair must be neat and long-haired practitioners
must tie their hair
3. Practicum is carried out for 2.5 hours according to the predetermined schedule
4. Practitioners must be present 10 minutes before the practicum begins.
5. The tardiness of the practitioner above 20 minutes will cause the practitioner not
to be allowed to take part in the practicum activities in the module that is being
carried out.
6. Practitioners can carry out practicum after getting instructions from the Practicum
Assistant
7. During the practicum, Practitioners are PROHIBITED:
• Eating, drinking and smoking
• Making noise in the room
• Change Software or Hardware configuration
• Leaving the room without the permission of the Practicum Assistant
• Using a Smart Phone without the permission of the Practicum Assistant
• Any inappropriate actions taken during the practicum
8. Implement "special rules", the flow of practicum activities in accordance with the
procedures set by each laboratory.
9. Practitioners who do not attend practicum due to illness, incidents or accidents,
worship or campus activities permitted by the Central Student Affairs must report
to the OA line seelabs a maximum of 3 days after the absence, or 3 days before
for those who perform umrah worship.
10. If the Practitioner violates rules 1 through 9 above, the Practitioner will be subject
to sanctions in accordance with applicable regulations.

Laboratorium Dasar Komputer Telkom University vi


B. Practicum Assessment System
1. One practicum course in the Faculty of Electrical Engineering consists of 12
practicum modules with the percentage of assessment according to the number
of modules of each practicum course given.
2. Specifically, the practicum assessment system for students who take practicum
courses at the Faculty of Electrical Engineering follows the following rules:
a. First Condition
Practicum courses consist of:
a. 1 practicum subject, totaling 12 practicum modules
b. 2 practicum subjects, 6 practicum modules each
c. 3 practicum subjects, 4 practicum modules each
• Students are given tolerance not to attend Practicum, only 1 (one) meeting
of the entire practicum
• If the absence exceeds the provisions of the above points, the
practicum course grade is worth E
b. Second Condition
The practicum course consists of 4 practicum subjects, each with 3 practicum
modules.
• Students are required to attend all Practicum meetings
• If you do not follow the above provisions, the practicum course grade is E.
3. For students who repeat the practicum, they are required to confirm the value of
the practicum subjects that have been passed in the previous year to the
laboratory assistant during the value validation period.

Dean of the Faculty of Electrical Engineering


Bandung, 7 August 2023

Dr. Bambang Setia Nugroho, S.T., M.T.

Laboratorium Dasar Komputer Telkom University vii


LABORATORIUM DASAR KOMPUTER
Engineering School – Telkom University
Gedung TULT lantai 10 ruang 10.04
Jl. Telekomunikasi No.1, Terusan Buah Batu, Bandung 40257

LETTER OF REVISION
I the undersigned
Name : Dr. Rahmat Awaludin Salam, S.Si., M.Si.

NIP : 14890058
Occupation : Algorithm and Programming Practicum Advisor

Hereby declare that the module for Algorithm and Programming Practicum for
Electrical and Physics Engineering Program has been revised with details as stated below:
No Module Revision Description Last Revision Date
1 Module 1 Addition of step folder exceptions
2 Module 2 Added explanation about "\t", "//". As
well as the addition of how to
implement the type of formation
type. August 7, 2023
3 Module 3 Changes in the structure of branching
material and the addition of
branching theory
4 Module 1-11 Cleaning up punctuation errors,
effective sentences, and typos. As
well as highlighting the coding

Bandung, August 7, 2023

Approved, Aware,
Laboratory and Studio Basic Computing Laboratory
Head of Affairs, Assistant Coordinator,

Dr. Rahmat Awaludin Salam Vincentius Jason Samhadi


NIP 14890058 NIM 1102213187

Laboratorium Dasar Komputer Telkom University viii


TABLE OF CONTENT

INTRODUCTION ......................................................................................................................................................... i
LETTER OF STATEMENT ........................................................................................................................................ iii
VISION AND MISSION OF ELECTRICAL ENGINEERING FACULTY ......................................................... iv
VISION AND MISSION OF ELECTRICAL ENGINEERING PROGRAM....................................................... v
LABORATORY RULES FOR ELECTRICAL ENGINEERING FACULTY TELKOM UNIVERSITY ............. vi
LETTER OF REVISION............................................................................................................................................ viii
TABLE OF CONTENT ............................................................................................................................................... ix
ASSISTANT OF DASKOM LABORATORY 2023/2024 ................................................................................... x
MODULE 1 : IDE INSTALLATION AND ALGORITHM INTRODUCTION ................................................ 1
MODULE 2 : DATA TYPE AND ALGORITHM COMPONENTS .................................................................11
MODULE 3 : BRANCHING ...................................................................................................................................18
MODULE 4 : LOOPING..........................................................................................................................................24
MODULE 5 : FUNCTION .......................................................................................................................................29
MODULE 6 : ARRAY ...............................................................................................................................................34
MODULE 7 : SORTING ..........................................................................................................................................39
MODULE 8 : SEARCHING .....................................................................................................................................46
MODULE 9 : RECURSIVE ALGORITHM ............................................................................................................49
MODULE 10 : FILE HANDLING...........................................................................................................................51

MODULE 11 : BASIC TECHNIC ON WRITING REPORT ............................................................. 65


BIBLIOGRAPHY ....................................................................................................................................... 70

Laboratorium Dasar Komputer Telkom University ix


ASSISTANT OF DASKOM LABORATORY 2023/2024

Assistant
No NIM Assistant Name Contact ID Line
Code
1 1102210135 Abdillah Nur Isnaini ABD 085254648494 abdillah729

2 1101213133 Adam Wisnu Pradana AWP 081332938169 adamwisnup

3 1102223029 Agus Miftah Parid GUS 082119580837 mifthprd

4 1101224317 Ahmad Syaiful Bahri BRI 081217028937 a_s_r_rbahri

5 1106220025 Ahmed Albatsa AMG 081390831098 stuckin16

6 1101210384 Alfarelzi EZI 085155288185 farel_zi31

7 1102213058 Alif Rizky Dimandani LIP 085791356223 alifrizky100203

8 1101223078 Alika Widuri Kartika AKA 081910346047 alikaawk

9 1102223047 Aliyus Hedri ALY 082388488916 alyhdr12


10 1101223083 Aliza Nurfitrian Meizahra ALL 081210655576 alizaaja24

11 1101210339 Alvaro Ahmad Firdaus ALV 081249495558 alvaroahmadf2148


12 1101210242 Amiruddin Zakaria Al-Hanif AZA 085156246985 amiruddin.za

13 1105210039 Andini Windy Rande AWR 081347540190 andini.wrande


14 1104213040 Arsyad Faturrahman ARF 081222672984 arsyadftr

15 1102223027 Aswangga Pandita Sadu WGG 082337495615 aswangga03

16 1102223037 Athirah Muthiah Marzuqah THI 082292062883 athirahmth


17 1101223209 Aulia Ramadhani LLY 085649100095 Lily_elui

18 1101210293 Bayu Dwi Pangestu BDP 085155477011 bayudpn

19 1105223102 Cantik Zelda Herawan EZL 085759066922 cantik_zldh

20 1102223269 Danur Herlambang DNR 081395782437 danurh222

21 1105223068 Darla Gempita Darris Purba DAR 088263589854 darlaoreki

22 1106220009 Dega Pradipta Ramadhan DPR 089529438818 degapr

23 1104223013 Dennytan Raharjo TAN 081395882733 dentan77

24 1104223146 Dhea Aisyah Putri DEY 081250770473 dheaaisyyy

25 1101224329 Dhiya Isnavisa DHY 085213696428 diarcwantofly

26 1102223167 Dimas Bima Aditya MAS 081275554718 massdimm_

27 1102213044 Evander Ricardo Manuel VAN 08112260388 evanderrichard

Laboratorium Dasar Komputer Telkom University x


28 1102213317 Fallerina Ribka Angela FLL 082138161039 ribtams29

29 1104223057 Farhan Oktavian IAN 085861090100 me.ahan

30 1104223083 Farrine Fadhirra Fasya RIN 082127692615 fadhirra30

31 1102223258 Garry Nelson SOH 081261469886 gn2004

32 1102213040 Ghufron Andriansyah GAA 081231717659 andriansyahh.29

33 1104213066 Henny Mar'atus Sholihah NNY 082111204181 hennymaratus03

34 1102223230 Hisyam Aqiel Sadzilli OIL 0895389942605 hisyamaqiel41

35 1102213020 Ikhsan Habib BIB 082288130402 habibikhsan

36 1102210086 Ilhaam Zaidaan Taufiqullah JAY 081318392846 081318392846

37 1101223028 Indi Viska Rahmasari VIS 085802253573 indiviska

38 1104220015 Junaidi Rahmat JIN 082292625290 hyakkimaru_4

39 1102223024 Justin Fairman Tan JFT 081277991505 justinft

40 1105220073 Lathifah Husnun TIP 085846522753 thifahus27


41 1101210153 Marshaniswah Syamsul MNS 0885258098757 chaca_niswa

42 1102213061 Mayco Ikhsan Hanafi MYC 081218918438 aselemeleketebuterer

43 1102213098 Mazaya MZY 082298311361 mazaya2004

44 1102213077 Michael Oktavian EON 085947340132 mr.ekel

45 1102223020 Mohamad Rifan Kasyiful Asrar FAN 085156984289 mrifanka

46 1104220063 Muh Zaidan Fauzan FYN 082123870889 ____ea


Muhamad Al Fitra Zulfikhar
47 1102213038 MAI 085972912455 zulakbar1412
Akbar
Muhamad Bahrul Muflih
48 1102213156 BHL 089604162335 littleshitt
Nurhabib
49 1101220021 Muhammad Afwan ONE 081297285194 ice17845
50 1102210215 Muhammad Aushaf Al Farras ALF 081347589812 alfalpha_

51 1102223064 Muhammad Azmi Anfasa Rizqi AAA 081387727480 ikercasillasrma

52 1101210429 Muhammad Dawwam WAM 081211695199 wm3611

53 1102223233 Muhammad Ferdiansyah PER 081293393183 frtwinz

54 1102213056 Muhammad Iqbal MIQ 089654904115 10000ball


Muhammad Nabil Arifiandi
55 1104220154 NST 081212115707 nabil150304
Tambunan
Muhammad Pachla Tigusti
56 1104220014 CLA 081779016013 pachlaa
Agung

Laboratorium Dasar Komputer Telkom University xi


57 1101210178 Muhammad Rafi Ediananta REN 08114444020 mrafi.ediananta
Muhammad Rafi Mahfuz
58 1101213355 XCX 087725006286 m.ra.m.s
Setyagraha
59 1102224211 Muhammad Raihan HAN 082128947744 raihanxx5

60 1101210282 Muhammad Reza Aditria REZ 081394589119 rezaaditria


Muhammad Zidane Naufal
61 1102213103 RAM 085155086785 zidane17naufal
Ramadhan
62 1101224341 Nahda Nabila BIL 085271950028 Pnn12

63 1101223205 Natasha Fedora Barus NFB 081232644668 natashafbarus

64 1101220356 Nathan Aryasatya Andhika NTR 087824692740 nathan_aryasatya

65 1102213096 Naufal Rayhan Ali Rahman RAR 081229280741 naufalrayhan5703

66 1102223133 Ni Kadek Cindy Sriastiti CYN 0895394594943 cindy.sriastiti


67 1105213019 Ni Luh Putu Sri Diantari OTU 081999857285 putuluhtudiantari
Nur Muhammad Faza Dwi Fajar
68 1104223009 FAZ 082243519148 fxfyfaza
Ramdhani
69 1104213030 Nyimas Anggun Barokatillah NAB 081902506111 anggun1524

70 1101213457 Rahma Khairany RKH 081260382579 rahmakhairanyy


71 1101213051 Raihan Radhitya Setiawan RHN 082127667491 raihanradhitya
Rasyad Rifatan Rahman
72 1102224221 RAD 082255112501 rasyadpatianom
Dingang Patianom
73 1106220039 Raudhah Nurul Auliya OYA 082238631162 Aul_iya

74 1104223097 Rendy Ryan Renaldi NOA 081324427030 rendyryanr

75 1102223153 Reyhan Andhata Pratama RAP 081256288031 gakwtggakmakan


76 1101213117 Reynaldhi Tryana Graha REY 085156964564 reynaldhi21

77 1101210431 Rifky Agung Febrian IKI 081214718236 rifky.5159

78 1102210312 Riska Nuraina Zalsabila RIS 085171161325 riskanurainaz


79 1105220065 Riza Aria Komara RIZ 087830350963 laukemas335

80 1101220030 Rizq Arthur Mahesatama ARC 081315434313 rizqart


81 1104213047 Salim Ammar Rasyid LIM 085802657969 ammar21juni2002

82 1101210343 Sazqia Aulia Palad QIA 085280555073 Sazqiaa_aulia

83 1104220143 Shedy Indra Maulana LEX 087784173073 arghh_nju


84 1105210013 Talita Sri Indrayuni TAL 085851219727 talitasindr

85 1102223051 Teguh Patriananda TGH 087885538877 patrianandateguh

Laboratorium Dasar Komputer Telkom University xii


Vincentius Adisurya Fransisco
86 1102213060 CEN 082311457280 chotix96
Antu
Vincentius Artyanta Maheswara
87 1102223079 TNT 082322512553 artya121212121212121
Purba
88 1102213187 Vincentius Jason Samhadi VIN 089654830223 vincjason

89 1105213021 Wina Nur Annisa WNA 085842186620 winanurannisa

90 1104213027 Zahira Aulia Husniah JHS 081289312727 gajahkuning


91 1102210105 Zaidan Fitra Baihaqi ZAQ 081280041558 zaidanfit26

Laboratorium Dasar Komputer Telkom University xiii


MODULE 1 : IDE INSTALLATION AND ALGORITHM
INTRODUCTION
Practicum Aim
1. Learn how to install Visual Studio Code
2. Understand the concept of algorithms and their notations.
3. Understand the algorithm design of a
4. Understand
program how to make flowchart
floflowcharts
Basic Theory :

IDE

IDE (Integrated Development Environment) is a computer program that has


several facilities needed in software development. The purpose of the IDE is to provide
all the utilities needed in building software.

An IDE, or can freely be translated as "Integrated Development Environment",


at least has features:

• Editor, which is a feature to write source code from a software.


• Compiler, which is a facility to check the syntax of the source code and then
change it in binary form according to machine language.
• Linker, which is a feature to unite binary data from some source code generated
by the compiler so that the binary data become one unit and becomes a
computer program that is ready to be executed.
• Debugger, which is a feature to test the running of the program, to look for
bugs/errors contained in the program

To a certain extent, modern IDEs can help provide suggestions that speed up
writing. At the time of writing the code, the IDE can also show the parts that contain
errors or doubts.

Dasar Komputer Laboratory will use the Visual Studio Code IDE during the lab work.
Here's how to install the Visual Studio Code IDE.

Laboratorium Dasar Komputer Telkom University 1


After Visual Studio Code has been downloaded, double click on its installation file.

After that choose I accept and click next.

Determine where Visual Studio Code will be installed. By default, this program will be
installed in the C:\Users\Admin\AppData\Local\Programs\Microsoft VS Code. After
that click “Next”.

Specify the location of the folder to put the Visual Studio Code files in, then click
next.

Laboratorium Dasar Komputer Telkom University 2


There are several types of installation menus in "Select Additional Tasks". Check all the
options except the Add “Open with Code” option, then click “Next”.

Make sure all the previously selected options are correct.

Wait until the installation process is complete.

Laboratorium Dasar Komputer Telkom University 3


Click “Finish” if the installation is finished.

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


gcc/ and download it according to the specifications of each computer.

Click on the Create button

Laboratorium Dasar Komputer Telkom University 4


Next, select the edition according to your existing system specifications.

By default, tdm-gcc will be installed at C:\TDM-GCC-XX and then click next to continue
with the install without changing any rules.

If the installation is complete, it will display the words completed successfully, click next
and finish.

Laboratorium Dasar Komputer Telkom University 5


Once the tdm-gcc installation is complete, open Visual Studio Code and switch to the
extensions page, and look for the C/C++ Extension Pack and click Install.

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

After Code Runner is installed, then right-click on the Code Runner extension and click
Extension Settings. Then look for options like the image above to run Code Runner in
the Visual Studio Code terminal.

In using Visual Studio Code, errors are often encountered in outputting a program. This
is caused by Windows security that prohibits running or executing the program file.
Windows automatically reads every folder to 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 exception folder step:
1. Go to Windows Settings
2. Go to Windows Security -> Threats and exclusions

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


4. Click Add or remove exclusions

Laboratorium Dasar Komputer Telkom University 6


5. Add an exclusion 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)

• Select or create a folder that will be used as a place to store the program

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

Laboratorium Dasar Komputer Telkom University 7


ALGORITHM

Algorithm is a series of steps that are precise, detailed, and limited in solving
problems. Right means that the step is always right to solve the problem. Detailed
means that the steps are detailed and can be executed by the computer. Limited means
that one day the step must stop. If the "never" step stops, the name is 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 perimeter and the input as length and width.
After that, you must determine how the perimeter of the rectangle is calculated based
on length and width data.

Circumference = length + width + length + width

or

Circumference = 2x (length + width)

You can enter the algorithm as follows :


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

Algorithms are not always expressed in human language as exemplified earlier.


Often the algorithm is expressed in the form of pseudocode (pseudocode) or a
flowchart.

1. Pseudocode (Pseudocode)
Pseudocode is a form of an algorithm that uses various notations intended to
simplify the form of human sentences. For example, a sentence like "Calculate the
circumference of a rectangle using the formula 2x (length + width)" can be simplified
to: circumference = 2x (length + width).
Pseudocode is often oriented towards certain programming languages. The
following example shows a pseudocode oriented in the Pascal programming language
(pseudopascal).
Algorithm (Pseudopascal)

Circumference of rectangle
Program

Laboratorium Dasar Komputer Telkom University 8


Dictionary :
p, l, k : integer

Algorithm :
output (‘Length = ‘)
input(p)
output (‘Width = ‘)
input (l)
k  2*(p+l)
output(‘Circumference of
rectangle = ‘, k)

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 stated
with a line with an arrow.
Here are some instructions that must be considered in making a flowchart:
1. Flowcharts are drawn from the top to bottom page and from left to right.
2. The activity described must be carefully defined and this definition must be
understood by the reader.
3. When activities begin and end must be clearly defined.
4. Every step of the activity must be described using verb descriptions, for example
calculating sales tax.
5. Every step of the activity must be in the right order.
6. The scope and range of the activity being described must be explored carefully.
The branches that interrupt the activity being described need not be drawn on the
same flowchart. The connector symbol must be used and the branching is placed
on a separate page or completely eliminated if the branching is not related to the
system.
7. Use standard flowchart symbols.

Here are the standard symbols for flowcharts.

Shape Symbol Description


Name
Flow Line Stating the course of a process.

Laboratorium Dasar Komputer Telkom University 9


On-Page State the connection from the process to the other process
Connector in the same page.

Off-Page State the connection from the process to the other process
Connector on a different page.

Process States an action (process) carried out by the computer.

Decision Indicates a certain condition that will produce two


possibilities, namely YES or NO.

Pre-defined State the other procedures that have been made in the
Process diagram.

Terminator State a start or end to a program.

Input / State the input or output process regardless of


Output the type of equipment.

The following is an example of a flowchart calculating the perimeter of a


rectangle.
Start

Input the length of the


rectangle

Input the width of


the rectangle

Circumference = 2x(length+
width)

Display the
circumference of
the

End

Laboratorium Dasar Komputer Telkom University 10


MODULE 2 : DATA TYPE AND ALGORITHM COMPONENTS

Practicum Aim
1. Understand the general form of algorithms and their implementation in C
language.
2. Make a simple program that involves I/O, assignments, variables, constants,
expressions, and formed data types.
3. Understanding the types of data in the algorithm and its equations in C.

Basic Theory :

1. Programming Language Structure C


In C language, the program structure consists of functions. Following is the
general structure of the C language.
PROGRAM STRUCTURE

// main
function
main(){
/*statemen */
}

// other function
Other_function(){
/* statemen */
}

2. Variables and Constants


Variables and constants are names that state a place in computer memory and
contain a value. The contents of the variable can be changed at any time when
the program is executed. While constants cannot be changed when the
program is executed. Important things to consider in naming variables and
constants include:
▪ must start with the letters of the alphabet (A..Z, a..z) or underscores (_);
▪ the next character can be letters, digits or underscore characters (_);
▪ the maximum length of an identifier is 32 characters if more then the initial
32 characters are considered;
▪ lust not use spaces;
▪ lust not use arithmetic operators (+ - / *%);
▪ lust not use special characters such as:,; # @ $ & and (.);
▪ language C is case-sensitive, so capital letters and non-capital letters are
distinguished.

Laboratorium Dasar Komputer Telkom University 11


3. Data Type
Data type is the type of variable used in the algorithm. Here are some types of
data.
a. Int: Express integers between -326767 to +32767
Example : 1 0 3 -5 -7
b. Float : Express real number between 10-38 to 1038.
Example : 1,1 1,3 -9,2
c. Char : Express a characters.
Example : A, f , 9 , or *.
d. Bool : Express logical value (true or false).

4. Arithmetic Operations
For arithmetic operations only int and float data types can be used. The
following operators are available arithmetic:
a. Multiply ( * )
Used to multiply two numbers.

Laboratorium Dasar Komputer Telkom University 12


b. Divide ( / )
Used to divide two numbers
c. Add ( + )
Used to add two numbers.
d. Reduce ( - )
Used to reduce two numbers
e. Modulo ( mod )
Mod used to find the remainder of the division for two numbers. The mod
operator in C is "%". The mod operation can only be used by data of type
int.
Data Type Example

Int % Int = Int 6%4= 2 → {6=4x1+2}


8%5= 3 → {8=5x1+3}
-5 % 3 = -2 → { 1 = 3 x (-1) + (-2) }
-3 % 2 = -1 → { -3 = 2 x (-2) + (-1) }
5. Struct
Struct is a data type created by the user. This type is made because there is a
relationship between variables which when combined have a common purpose.
To create the formed data type, the keyword "struct" is used. One example of
the type of formed data is students, where students have names, numbers,
majors, and grades.

Program Example :
a. Display Sentences
#include <stdio.h>
int main ()
{
printf (“Hello World \n”);
return 0;
}

The output of the above program is: Hello World


Explanation:
• Header files (ending in .h) are files that contain function prototypes, constant
definitions, and variable definitions. Prototype functions in the form of the
title of a function that is equipped with arguments and types of arguments
as well as the type of return value for the function that provides the return
value.

Laboratorium Dasar Komputer Telkom University 13


• The #include processor is a command used to set the compiler to read the
header file that is included behind the include word during compilation.
• main () is a function that will be run first when the program is executed. The
word int in front of main () states that the program returns a value of type
int.
• The return value of the program is determined by the return statement. In
the program, return 0 states that the return value of the program is zero.
Zero value is usually used to declare that the program successfully carried
out the tasks it carries.
• Each statement in C is written with a semicolon (;) ending. In the above
program, there are two statements, namely: printf ("Hello World \ n"); and
return 0;
• "\n" will cause the cursor to move to the next line after Hello World is output
b. Add values to the variables
There are 3 ways to enter a value into a variable, namely :
❖ Assignment (value entered into the variable directly)

C Algoritma

a=7; a7

❖ Input using scanf() command

C Algoritma

#include <stdio.h> Dictionary :


main ()
x,y,z : integer
{
int x, y, z; algorithm :
printf ("Number 1 ="); output ('Number 1 =') input (x)
scanf ("%d", & x);
output ('Number 2 =') input (y)
printf ("Numbers 2 =");
scanf ("%d", & y); z <- x + y
z = x + y; output ('Number 1 + Number
printf ("Numbers 1 + Numbers 2 = %i 2 =', z)
\n", z);
return 0;
}

Laboratorium Dasar Komputer Telkom University 14


❖ Use of constants #define is used to define a variable (pin input-
C output, etc.) with a new variable name so that in
making our program it is easier to remember
#include <stdio.h> the name of the variable. Therefore, try to
#define phi 3.14 define a variable using a variable name that
int main () { reflects its function.
int r;
float area;
% x.f serves to display the x
printf(“radius =“);
number behind the decimal
scanf (“%d”,&r);
area = phi*r*r; point of the output variable.
printf(“Area of Circle = %.2f In the example beside, printf
\n”,area); ("Circle Area =% .2f \ n",
return 0; area); will display 2 decimal
} places of the broad variable.

c. Formed data type


The following is an example of the type of formation of student biographical
data which consists of several variables, such as: name, department, NIM, and
class.
C Algorithm
#include <stdio.h> Type biodata:
struct biodata
{ <name, Department, NIM,
char name[20], major[20], nim [20], class Class: string>
[20]; Dictionary :
}b;
int main () b : biodata
{ Algorithm :
printf("Name\t:");
gets(b.name); //input data in struct output(‘Name : ‘)
printf("Major\t:"); input(b.name)
gets(b.major); output(‘Department : ‘)
printf("NIM\t:");
input(b.j Department)
gets(b.nim);
printf("Class\t:"); output(‘NIM : ‘)
gets(b.class); input(b.NIM)
printf("Your Biodata:\n"); output(‘Class : ‘)
printf("Name\t:%s\n", b.name); input(b.Class)
printf("Major\t:%s\n",b.major);
printf("NIM\t:%s\n",b.nim); output(‘Your Biodata : ‘)
printf("Class\t:%s\n",b.class); output(‘Nama : ‘,b.name)
return 0; output(‘Jurusan : ‘,b.Department)
} output(‘NIM : ‘,b.NIM)
output(‘Kelas : ‘,b.Classs)

Laboratorium Dasar Komputer Telkom University 15


Notes :
• The gets () function is used to input a string. If you use the scanf () function when
inputting a string, it will only be read until space is found. For example "Cristiano
Ronaldo", it will only read Cristiano, while Ronaldo is unreadable because before the
word the program has found a space.
• Each input with scanf and output with printf must include the format determinant
of the input and output. For example, we will enter the value 5 (integer) into the
variable x so we will write: scanf ("% i", & x); where "% i" is the format determinant
for integer data types. Following are some of the format determinants that are often
used in the C programming language.

• "\t" will add spaces that are the same distance as tabs or you can say \t is a
representative of the tab character

• "//" this symbol is used to mark a one-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.

Another example of writing a formed data type

C
#include <stdio.h>
struct modulo
{
int x, y;
};
int main()
{
struct modulo mod;
printf("Numbers 1 %% Numbers 2\n");
printf("Sample Insert:\n");
printf("10 4 \n");
printf("Modulo Result: 2\n");
printf("Insert Numbers: \n");
scanf("%d %d", &mod.x, &mod.y);
printf("Modulo Result: %d", mod.x % mod.y);
return 0;
}
The application of form data types can also be done like the program above. It
is useful to simplify a program and facilitate the work in preparing a program, so
that it can be efficient in preparing a program. The formed data type uses the name

Laboratorium Dasar Komputer Telkom University 16


Structure as an alias to declare the variable that contains the formed data type, so
it only needs to call struct structureName variableName.

Data Type Determinant


Integer %d, %i
floating point
• Decimal Form %f
• Rank Form %e
• Shorter between decimal and rank %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

By default, the C language displays a decimal number with 6 decimal places.


That is if what is written is 4,323, then what is displayed becomes 4,323000. The
printf command has special rules to set the C language to display the number
of decimal places. We can add 3 writing methods to the% f pattern. Where the
format is as follows:

Format

%f Will display a 6 digit number behind the comma.

%xf Will display as many as x digits with spaces as separators

%0xf Will display a number of x digits with 0 as the separator

%.xf Will display x digits behind the comma

* with the note x filled with the desired number.

Laboratorium Dasar Komputer Telkom University 17


MODULE 3 : BRANCHING

Practicum Aim

1. Understand the form of branching


2. Make a simple program using branching sort
3. Solve a case regarding branching sort and implement it into C Language

Basic theory :
Boolean operations are logical operations that only return true or false. This operation
will often be used to determine the action to be carried out by the program (in
branching or repetition).
Operator
boolean Example Description
C Algorthm
== = a == b Is true if a is equal to b
< < a<b Is true if the value of a is less than b
<= ≤ a <= b Is true if the value of a is less than / equal to b
> > a>b Is true if the value of a is more than b
>= ≥ a >= b Is true if the value of a is more than / equal to b
!= ≠ a!=b Is true if the value of a is not the same as b

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
Operator AND on C is && Operator OR on C is ||
Operator NOT on C is ! Operator XOR on C is ^

a not a
False True
True False

Laboratorium Dasar Komputer Telkom University 18


Branching:

Branching is a method of selecting an action to be executed by the program based on


a given condition. There are various types of branching, namely:

1. if [Condition]--[Action]
In this method, the action will be performed when the if condition is true.

C Algoritma
#include <stdio.h> Program if One Action
void main()
Dictionary :
{
float gpa; gpa : floating
printf("Enter your GPA:"); Algoritma :
scanf("%f",&gpa); Output(‘Enter your GPA: ‘)
if(gpa>=2)
printf("Congratulations you passed");
Input(gpa)
if(gpa>3.5) if(gpa >= 2) then
printf("and Cum Laude"); Output(‘Congratulations you
if(gpa<2) passed ’)
printf("Sorry you didn't pass");
if(gpa > 3.5)then
}
Output(“and Cum Laude”)
if(gpa < 2)then
Output(“Sorry you didn't pass”)

The above program will display the graduation result according to the GPA
value entered. If the GPA value is more than equal to 2 and more than 3.5, it will
display "Congratulations you graduated and also got a Cum Laude degree". This
happens because the program checks the condition in each if, if the if is true then
the action in the if will be executed.

Laboratorium Dasar Komputer Telkom University 19


2. if [Condition]--[Action]
else --[Action]
In this method, the action will be performed when the condition is true.

C Algorithm
#include <stdio.h> Program if One Action
int num;
void main() Dictionary :
{ num : integer
printf("num: ");
scanf("%d",&num); Algoritma :
if (num%2==0) Output(‘number: ‘)
printf("even number "); Input(num)
else printf("odd number ");
} if(num mod 2 = 0) then
Output(‘even number’)
else Output(‘odd number’)

The program above will display "Even Numbers" if the bil value entered is even (an
even number means it is divisible by two or can be written bil % 2 = 0).
C
#include <stdio.h>
typedef struct BPJS {
int score;
}data;
int main()
{
data p1;
printf("Your score: "); scanf("%d",&p1.score);
if (p1.score >=75) printf("passed");
else printf("not passed ");
return 0;
}

The program above will display the graduation result according to the value
entered. Similar to the previous program, the action in if will be performed when the
condition is true, otherwise if the condition is false then the action in else will be
performed.
In addition, there is a new syntax, namely typedef which is one of the methods
in writing a type formation. It serves as the creation of an alias name for the specified
data type. It is usually used with structures to simplify the syntax of declaring the
type.

Laboratorium Dasar Komputer Telkom University 20


3. if [Condition]--[Action]
else if [Condition]--[Action]
else --[Action]

In this method, the action will be performed when the condition is true. If there is a
true condition, the program exits the branching system.
C
#include <stdio.h>
#include <string.h>
struct Session {
char uname_session[50];
int status;
}session;
int main()
{
session.status=0;
char uname[50], pass[50];
printf("Username : "); gets(uname);
printf("Password : "); gets(pass);
if (strcmp(uname,"Flowchart")==0 && strcmp(pass,"Kece")==0)
{
session.status=1;
strcpy(session.uname_session,uname);
printf("Login Successful\n");
printf("Please Continue\n");
}
else if(strcmp(uname,"Pemrograman")==0 && strcmp(pass,"Kece")==0)
{
session.status=1;
strcpy(session.uname_session,uname);
printf("Login Successful\n");
printf("Please Continue\n");
}
else
{
printf("Incorrect username or password\n");
}
if(session.status==1)
{
printf("Welcome , %s", session.uname_session);
}
return 0;

Laboratorium Dasar Komputer Telkom University 21


}

Unlike the previous program, there is an else if in the program above where the
action in the program indicates there is more than 1 condition given. If the condition
in if is true, then the action in the body of if is executed. If the condition in if is false,
then the program action will move to else if and check the else if condition. If else if
is true, then the action in the body of else if is executed. otherwise, if the condition is
false, then the action in else will be performed.
The program above will display the output "Login Success" if the username and
password entered match those in the program line above, namely "Flowchart" and
"Kece" or "Programming" and "Kece".
*note :
- if more than one action (in if or else) is to be done, then add "{" (before
the first action) and "}" (after the last action).
- You cannot use the = sign to compare strings. Comparisons are made
using the strcmp() function. The strcmp() function is in the header string.h.
So it is necessary to include the string.h header in the program using the
#include <string.h> command at the beginning of the program so that the
strcmp() function can be read. In addition to the strcmp() function, the
#include<string.h> header also contains the strcpy() function which is
used to copy the string pointed to by the source (including null characters)
to the destination.
- In the strcmp function (string1, string2) there are several return values,
including:
- 0 : if string1 equal to string2

Laboratorium Dasar Komputer Telkom University 22


- <0 : if string1 more than string2
- >0 : if string1 more than string2
- In the strcpy(destination, source) function, there is a rule that must be
carried out, namely the size of the variable in the destination must be the
same as the variable in the source. If the size of the two variables is not the
same, it can result in undefined behavior.

4. Case [variabel] of
C Algorithm
#include <stdio.h> Program Example of CaseOf
int i;
void main () Dictionary :
{ i : integer
printf("Input the sequence of days:"); Algorithm :
scanf("%d",&i);
switch (i) Output(‘Input the sequence of
{ days : ‘)
case 1:printf("Monday");break; Input(i)
case 2:printf("Tuesday");break; Depend on (i)
case 3:printf("Wednesday");break;
case 4:printf("Thursday");break; i = 1 : output(‘Monday’);
case 5:printf("Friday");break; i = 2 : output(‘Tuesday’);
case 6:printf("Saturday");break; i = 3 : output(‘Wednesday’);
case 7:printf("Sunday");break; i = 4 : output(‘Thursday’);
default :
i = 5 : output(‘Friday’);
printf("The number is out of the sequence
days’");break; i = 6 : output(‘Saturday’);
} i = 7 : output(‘Sunday’);
} else output(‘The number is
out of the sequence days’);

From the example above the action that will be carried out depends on the
value contained in the variable i, when i has a value of 1 then the program will display
the word "Monday" and so on until the number 7. The default function if cases 1-7 are
not met, then the default command will be run. Break functions to stop the action
being carried out in the case so that the action in the next case is not processed.

Laboratorium Dasar Komputer Telkom University 23


MODULE 4 : LOOPING

Practicum Aim

1. Understand forms of looping


2. Make a simple program using looping method in C language
3. Solve a case of looping method and implement it in C language

Looping
Looping in programming is used to repeat a particular block of code until it meets the
desired conditions. There are 3 main structures in the loop, which are as follows :
1. Initialization
Initialization is a condition at the beginning of the loop where we assign a value to
the counter variable.
2. Condition
Conditions are comparisons that must be met for the loop to run. As long as this
condition is met, the compiler will continue to iterate until the condition is not met.
3. Update Statement
The update statement is part of processing the counter variable in order to meet
the final condition of the loop.

Pre-Increment and Post-Increment


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

Laboratorium Dasar Komputer Telkom University 24


The difference between the two will look different when using the output command
like the example below:
Program Example Output
#include<stdio.h> i=0
void main()
{
i=2
int i=0;
// Contoh Post-Increment
printf("\ni = %d",i++); // i = 0
// Contoh Pre-Increment
printf("\ni = %d",++i); // i = 2
}

Description :

In the first printf command produces the value i = 0 because by using


postincrement it will return the value before adding. Conversely, the pre-
increment will return a value after making additions.

Note :
Conversely, if used to reduce the value of a variable it is called decrement, for example:
i-- or - i.

Following are the types of looping in the C programming language:


1. While loop
In this method, the action will be carried out as long as the condition is true
and will stop if the condition becomes false. In this iteration the number of
repetitions is not known with certainty.

Declaration C Algorithm Output

while(condition) #include<stdio.h> Example 1


int i;
{ programWhile 2
void main()
// action { 3
// action i=1; 4
// action while (i<=10) 5
{ 6
}
printf("%d\n",i);
i=i+1;
Dictionary : 7
i : integer 8

Laboratorium Dasar Komputer Telkom University 25


} Algorithm : 9
}
i1 10
While (i ≤ 10) do
Output(i)
ii+1

In the example above there is an action "i = i + 1" which will change the output
condition "i <= 10" to false (when i> 10) so that the loop will stop. This means "i
must have a value <= 10" so that true other than false.

2. Do while loop
In this iteration method, the action will be done at least once, this is because
the condition checking is done after the action is performed for the first time.
The action will continue as long as the condition is true and stop when the
condition is false. In this iteration, the number of repetitions is not known with
certainty.

Declaration C Algorithm Output

do{ #include <stdio.h> DoWhile Program 1


int i;
// action Example 2
void main (){
// action i=1; Dictionary : 3
// action 4
do{ i : integer
}while(condition) printf("%d\n",i); 5
i++; Algorithm : 6
}while (i<10); i  1 repeat 7
}
Output(i) 8
i  i + 1 until (i > 10) 9

Notes:
Statement i++ identical with i=i+1;

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

Laboratorium Dasar Komputer Telkom University 26


Declaration C Algorithm Output
for(initialization; #include <stdio.h> ForLoop Program 1
int i;
condition; Example 2
void main(){
update for(i=1; i<8; i++) Kamus : 3
statement){ printf("%d \n",i); 4
i : integer
// action } 5
// action Algoritma : 6
// action i traversal [1..7] 7
} Output(i)

Note :
- if you want to use decreasing method (ex. 10 → 1) use for(i=10; i>=1; i--)
- Example program to enter some data using looping
Sample program to input several data using looping method
C Description
#include <stdio.h> scanf () has the
#include <stdlib.h>
int result,n,i;
disadvantage of leaving "\
char name[100]; n" (new line) in the input
void main(){ memory, so that if there is
system("cls");
a gets () after scanf (), the
printf("The number of data: ");
scanf("%d",&n); gets () won't work. The
for (i=1;i<=n;i++) solution is to add getchar
{
() after scanf () which
printf("Result: ");
scanf("%d",&result);getchar(); functions to retrieve "\ n"
printf("name: ");gets(name); in the input memory so
}
}

system (“cls”); the function is to do a clear screen in gets () can work


the program . The system(“cls”) can be found in properly. The getchar ()
stdlib.h library. function is in the stdio.h
library

Laboratorium Dasar Komputer Telkom University 27


Control Commands
Control commands are used in a loop to change the loop execution results from its
normal state.
Below are the control commands for looping:
Command Program Example Output Description
#include<stdio.h> 1 Break command functions
int i;
2 to stop the looping process
void main(){
3 that is in progress. In the
Break for(i=1;i<10;i++){
if(i==7) break; 4 example beside the loop it
Command will stop when i is equal to 7.
printf("%d\n",i); 5
} 6
}

#include<stdio.h> 1 The continue command


int i;
2 functions to skip the
void main(){
for(i=1;i<10;i++){ 3 intended loop. In the
Continue if(i==7) continue; 4 example beside the
Command printf("%d\n",i); 5 program will continue
} 6 looping when i is equal to 7
}
8
9

Laboratorium Dasar Komputer Telkom University 28


MODULE 5 : FUNCTION
Practicum Aim
1. Understand the using of function in C programming.
2. Understand the structure of function in C programming.
3. Able to differentiate the kind of function parameter in C programming.
4. Able to make simple program using function in C programming.

Basic theory:
Functions are subprograms that are very useful in programming, especially for
large programs. For example, we enter the function of the area of the quadrilateral
prism. Then we only need to write the prism-wide formula once in the function without
having to write it repeatedly in the main program.
The following terms are often used in functions:
❖ Local variables: variables that can only be used for algorithms within the function

❖ Global variables: variables that can be used both in the main program and in

functions
❖ Actual parameters: parameters included when calling a function

❖ Formal parameters: parameters placed in the function header

Function Structure

The content of x
will correspond to
c
the variable a in
Header #include <stdio.h> the function and y
int add(int, int); will correspond to
int x,y; b in the function
Global Variable
void main(){
Function
invocation by printf("First number: ");
coupling it scanf("%d", &x);
printf("Second number: ");
Formal Parameters
scanf("%d", &y);
The data type of printf("Sum result = %d",add(x,y));
the output of the }
function or the
return value type
int add(int a, int b){
int result; The function will
result = a+b; return a value of
Local Variable the same type as
return result;
} its result type

Laboratorium Dasar Komputer Telkom University 29


Function
A function is a piece of code intended to carry out a specific task, the task requires
input information called parameters and usually, a function will return a value (return
value).
In writing a function, it is given a name/identifier, a formal parameter (the input
value is given a name and the type is explained), and a type of function is declared.
Functions can be created before or after writing the main program. If it is made
after writing main, then the prototype function must be written at the top of the
program.
How to call a function C Algorithm
Assignment a = adder(x,y) a  adder(x,y)
Output (printf) printf(“%d”,adder(x,y)) Output(adder(x,y))

a. Writing functions after the main program


C Algorithm
#include <stdio.h> Program Addition
int adder(int, int);/*Function Prototype*/
void main(){ Dictionary :
int x,y; x, y : integer
printf("First number : ");
scanf("%d",&x); Algorithm :
printf("Second number : "); Output(‘First number: ‘)
scanf("%d",&y);
Input(x)
printf("Result = %d",adder(x,y));
} Output(‘Second number: ‘)
int adder(int a, int b){ Input(y)
int c; Output(‘Result : ‘,adder(x,y))
c=a+b;
return c; function adder (a,b : integer)
} → integer
Dictionary:
c : integer
Algorithm :
c→a+b
This way of writing requires a prototype of the function, the purpose is as an
abstraction 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.

Laboratorium Dasar Komputer Telkom University 30


b. Writing functions before the main program
C Algorithm
#include <stdio.h> Program Addition
int adder(int a, int b){
int c; Dictionary :
c=a+b; x, y : integer
return c;
} Algorithm :
void main(){ Output(‘First number: ‘)
int x,y; Input(x)
printf("First number : ");
Output(‘Second number: ‘)
scanf("%d",&x);
printf("Second number : "); Input(y)
scanf("%d",&y); Output(‘Result : ‘,adder(x,y))
printf("Result = %d",adder(x,y));
} function adder (a,b : integer)
→ integer

Dictionary :
c : integer
Algorithm :
c→a+b

Void Function
The void function is a function that does not return a value or has no return
value. This function is widely used in the following 2 cases:
1. Display information on the screen so that it can be read by the user.
2. Functions with reference parameters, namely by sending the memory
address of a variable into the parameter.
C Output

Laboratorium Dasar Komputer Telkom University 31


#include <stdio.h> Example 1:
void numbr(int a){
Value: 10Positive
if(a>0)
printf(“Positive”);
else if(a<0) Example 2:
printf(“Negative”); Value: -22Negative
else printf(“Zero”);
}
void main(){ Example 3:
int x; Value: 0Zero
printf("Value: ");
scanf("%d",&x);
numbr(x);
}

Parameter
Parameters are data entered into a function which will then be used in the process
that is in the function. There are 2 ways to enter parameters in the C language:
❖ Pass by value, meaning that the data passed is only the value of a variable and
then stored in the local variable in the function. In other words, this method uses
2 different variables, so the variables in the actual parameters cannot be changed
in the function.
❖ Pass by reference, meaning that the data passed is the memory address of a
variable. In other words, this method uses the same variable, so changing the
value of a variable in a function can change the value of the original variable.
Following are examples of pass by value parameters and pass by reference
parameters:
Parameter pass by value Parameter pass by reference
#include <stdio.h> #include <stdio.h>
void exchange (int, int); void exchange (int*, int*);
void main(){ void main(){
int a,b; int a,b;
a=27; a=27;
b=7; b=7;
exchange (a, b); exchange (&a, &b); // Pass by
printf("Exchange results: reference
\n"); printf("Exchange results: \n");
printf("a = %d \n",a); printf("a = %d \n",a); printf("b =
printf("b = %d",b); %d",b);
} }
void exchange (int x, int y){ void exchange (int*x, int*y){
int temp; int temp;
temp=x; temp=*x;

Laboratorium Dasar Komputer Telkom University 32


x=y; *x=*y;
y=temp; *y=temp;
} }
Output : a=27 , b=7 Output : a=7 , b=27
Variable values are not changed The way to make the parameter pass by
because the variable in the actual reference is to use an asterisk (*).
parameter and the variable in the Meanwhile, the way to call the function is to
function are two different use an ampersand (&) in front of the
variables. reference variable.

Pointer
Pointers are features in C that are used to access and manipulate the memory
address of a variable. Pointer has 2 operators, namely:
1. Dereference operator (*), to provide the value (value) of a variable.
2. Reference operator (&), to provide the memory address of a variable.
#include <stdio.h> Output:
int main(){
Value: 5
int var = 5;
printf(“Value: %d\n”, var); Address: 2358860
printf(“Address: %u”, &var); /* Memory address values
} may change anytime */

An example of the application of a pointer program is that pointers can be used to


access and manipulate elements in arrays, including use in functions to operate on
arrays without sending the entire array as an argument.

Laboratorium Dasar Komputer Telkom University 33


MODULE 6 : ARRAY

Practicum Aim
1. Understand the purpose of using arrays.
2. Understand the meaning of string as an array of char.
3. Can create programs using one/two dimensional arrays.
4. Understand the intent of using an array of strings.
5. Can create programs using two-dimensional arrays.

Basic Theory :
Array is a structured data type that can store a lot of data with the same name
and occupy a place in memory in sequence and has the same data type. In this module
practicum, arrays are divided into 2 forms, namely one-dimensional arrays and
multidimensional arrays. Filling in the array starts at index 0.
Example: You want to enter 5 students' grades. Without arrays, you will create
5 new variables, namely student grades 1 to 5, but if you use arrays you only need to
use 1 variable.
Without Array With Array
#include<stdio.h> #include<stdio.h>
int score1,score2,score3,score4,score5; int score[100],i,n;
void main() void main()
{ {
printf("Score of Student 1= "); n=5;
scanf("%d",&score1); for (i=0;i<=n-1;i++)
printf("Score of Student 2= "); {
scanf("%d",&score2); printf("Score of
printf("Score of Student 3= "); Student-%d : ",i+1);
scanf("%d",&score3); scanf("%d",&score[i]);
printf("Score of Student 4= "); }
scanf("%d",&score4); }
printf("Score of Student 5= ");
scanf("%d",&score5);
}

Writing array variables :


Algorithm Variable Name = X
C
Notation
Index = [i]
X[i] Xi

Laboratorium Dasar Komputer Telkom University 34


1. One Dimension Array → Array Declaration: Type data_Variable Name[array size]
For Example : Int a [100]
Arrays can be illustrated as a locker. The followi ng is an illustrative example of
a one-dimensional array of integer data types of sizes 10 and 5 containing random
values.
Note that array size indicates the maximum limit of an array index. For example,
array [5], means that the array is filled to the maximum by 5 data, but can be filled in
by less than 5 data and cannot be filled by more than 5 data.

Array Element (contents of every locker) → 5 10 7 2 11 8 1 14 7 3


Array index (the locker number) → 0 1 2 3 4 5 6 7 8 9

Array Element (contents of every locker) → 5 10 7 2 11 Array [5] can be


filled by 5 data,
Array index (the locker number) → 0 1 2 3 4

Array Element (contents of every locker) → 5 10 7 Array [5] can be


filled by < 5 data,
Array index (the locker number) → 0 1 2 3 4

Array Element (contents of every locker) → 5 10 7 2 11 8 Array [5] can’t


be filled by >5
Array index (the locker number) → 0 1 2 3 4 5 data

Example programs using one-dimensional arrays :

C Algorithm
#include<stdio.h> Program array1dim
int a[100],i,n;
void main() Dictionary: :
{ a : array [1..100] of integer
printf("amount of Data= "); i, n : integer
scanf("%d",&n);
for(i=0;i<=n-1;i++) Algorithm :
{ Output(‘Input amount of data : ‘)
printf("Data -%d= ",i+1);
scanf("%d",&a[i]);
Input(n)
} i traversal [1..n]
} Output(‘Input data - ‘,i,’ : ‘)
Input(ai)

Arrays can also be used to store data with the type of construction (Struct).
The example in the following table (left) is a program used to store student data
consisting of student names, NIMs, and grades.

Laboratorium Dasar Komputer Telkom University 35


Array of record (struct) Array of char
#include<stdio.h> #include <stdio.h>
struct mhs { #include <string.h>
char name[20], nim[20]; char word1[100];
int grade; int length;
}; main() {
struct mhs a[100]; printf("Word 1 : ");
int i,n; gets(word1);
main() { length=strlen(word1)-1;
printf("Number of student : "); printf("Initial word : %s
scanf("%d",&n); \n",word1);
for (i=0; i<=n-1; i++) { printf("Reversed word : ");
printf("Student no-%d \n",i+1); for (length;length>=0;
printf("Name : "); length--)
fflush(stdin);gets(a[i].name); printf("%c",word1[length]);
printf("NIM : ");gets(a[i].nim); }
printf("Grade :");
scanf("%d",&a[i].grade);
}
printf("\n");
printf("Student’s Data \n");
for (i=0; i<=n-1;i++) { ❖ fflush (stdin) is used to empty the
printf("Student %d \n",i+1); burffer input. Without fflush
printf("Name :%s \n",a[i].name);
printf("NIM : %s \n",a[i].nim); (stdin), the gets () function that
printf(“Grade : %i\n",a[i].grade); run is the first gets () function
} only, while the second gets ()
return 0; function and the rest will not be
}
run.
While the example in the right-hand table is an example of using strings as
arrays. The program functions to reverse a sentence. The syntax strlen () is used to
find the length of a string (many char's in that string.

2. Multi-Dimensional Array
→ Array Declaration : Type data_Variable Name[array1 size][array 2 size]
The concept of a multidimensional array is the same as a one-dimensional
array, the difference is the index limit of this array is more than one. The array
declaration above is an example of a multidimensional array with two dimensions.
This two-dimensional array can be illustrated as a matrix of size m x n.

The following is an illustrative example of an array with two dimensions,


where the 1 - m range is for rows and the 1 - n range is for columns

Laboratorium Dasar Komputer Telkom University 36


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 a two-dimensional array :


C Algorithm
#include <stdio.h> Program array2dim
Dictionary: :
int i,j,m,n,mat1[50][50];
int mat2[50][50],mat3[50][50]; mat1,mat2,mat3 : array [1..50, 1..50]
of integer
int main() { m,n,i, j : integer
printf("Number of line = ");
scanf("%d",&m);
Algorithm :
printf("Number of column= "); Output (‘Number of line = ‘)
scanf("%d",&n); input(m)
printf("Matrix 1 \n"); Output (‘Number of column= ‘)
for (i=0; i<=m-1;i++)
for (j=0; j<=n-1;j++) {
input(n)
printf("line %d, column %d = Output (‘Matrix 1’)
",i+1,j+1); i traversal [1..m]
scanf("%d",&mat1[i][j]); j traversal [1..n]
}
printf("Matrix 2 \n"); Output(‘line‘,i,’ column ‘,j,’ = ‘)
for (i=0; i<=m-1; i++) Input(mat1i,j)
for (j=0;j<=n-1;j++) { Output (‘Matrix2)
printf("line %d, column %d = i traversal [1..m]
",i+1,j+1);
scanf("%d",&mat2[i][j]); j traversal [1..n]
} Output(‘line ‘,i,’ column ‘,j,’ = ‘)
Input(mat2i,j)
for (i=0;i<=m-1;i++) i traversal [1..m]
for (j=0;j<=n-1;j++) {
mat3[i][j]=mat1[i][j]+mat2[i][j]; j traversal [1..n]
} mat3ij  mat1ij + mat2ij
printf("Result of Matrix’s Sum \n"); Output (‘Result of Matrix’s Sum’)
for (i=0;i<=m-1;i++) {
i traversal [1..m]
for (j=0;j<=n-1;j++)
printf("%d ",mat3[i][j]); j traversal [1..n]
printf("\n"); output (mat3[i][j])
} {move line }
return 0;
}

Laboratorium Dasar Komputer Telkom University 37


Array Of String
Array of String is a two-dimensional array of characters. Strings are similar to
arrays. Usually, array sizes are fixed, whereas strings can have several variable elements.
Arrays can contain any data type (char, int, even other arrays) while strings are usually
ASCII characters ending in NULL (0) characters. In general we allow random access to
individual array elements. On the other hand, we usually process strings in sequence
character by character from beginning to end.

C Program
#include <stdio.h>
#include <stdlib.h>
main(){
char names[20][20];
int n, i;
printf("input how many names :");
scanf("%d",&n); getchar();
printf("input names : \n");
for(i=0;i<n;i++){
printf("name %d :",i+1);
gets(names[i]);
}
printf("\n [OUTPUT]\n");
for(i=0; i<n; i++){
printf("name %d is %s \n",I+1, names[i]);
}
}

Laboratorium Dasar Komputer Telkom University 38


MODULE 7 : SORTING
Practicum Aim
1. Understand the logic of sorting by using four methods :
counting, selection, insertion, dan bubble.
2. Able to implement sorting logic into programs using C language

Sorting:

Sorting in this module is interpreted as a sorting algorithm. Many methods can be used
in sorting data. Sorting can be done by ascending or sorting from the smallest value
to the largest value and descending or sorting from the largest to smallest value. But
in this practicum, 4 methods will be discussed, namely:

1. Counting sort
This is how to use Counting Sort :
a. Create a new array with a range of minimum to maximum values from the
old array.

0 2 1 3 9 3
array A
0 1 2 3 45

Suppose there are 6 data in array A from that data, it can be concluded that
the minimum value is 0, and the maximum value is 9, then an array B is made
with 10 tables (index 0 - 9)
b. Furthermore, the contents of array A will be transferred to array B based on
the frequency of the data contained in array A array B

Array B 0 0 0 0 0 0 0 0 0 0
0 1 2 3 4 5 6 7 8 9

Laboratorium Dasar Komputer Telkom University 39


1 1 1 2 0 0 0 0 0 1
0 1 2 3 4 5 6 7 8 9

c. Then move the contents of array B to array A

C Algorithm
#include <stdio.h> Program countSort
int i, j, total, max, min, idx;
Dictionary:
int main () { DATA, TEMP : array [1..255] of
printf("Banyak data: ");
integer i, j, total, max, min, idx :
scanf("%d", &total);
integer
int DATA[total]; //memberi ukuran Algoritma :
pada array DATA Output(‘Masukkan banyak data : ‘)
Input(total)
for (i = 0; i < total; i++) {
printf("Data ke-%d: ", i+1); i traversal [1..total]
scanf("%d", &DATA[i]); Output(‘Masukkan data ke-‘,i,’ : ‘)
if (i == 0){ Input(DATAi)
max = DATA[i]; if (i = 1) then
min = DATA[i];
} max  DATAi
else { min  DATAi
if (DATA[i] > max) max = DATA[i]; if ( DATAi > max) then
if (DATA[i] < min) min = DATA[i]; max  DATAi
}
} if ( DATAi < min) then
min  DATAi
int TEMP[max - min + 1]; i traversal [min..max]
TEMPi-min  0
//empty the array temp
for (i = min; i <= max; i++) i traversal [1..total]
TEMP[i - min] = 0; TEMPDATAi-min  TEMPDATAi-min +
1
//first counting sort process – idx  0
counting the data frequency
i traversal [max..min]
for (i = 0; i < total; i++)
TEMP[DATA[i] - min]++; j traversal [1.. TEMPi-min]
DATAidx  i

Laboratorium Dasar Komputer Telkom University 40


//second counting sort process – idx  idx + 1
filled the main array
i traversal [1..total]
idx = 0;
for (i = max; i >= min; i--) Output( DATAi )
for (j = 1; j <= TEMP[i - min]; j++)
{
DATA[idx] = i;
idx++;
}

//displays the sorting results


for (i = 0; i < total; i++)
printf("%d ", DATA[i]);

2. Selection sort
This is how selection sort work :
a. Look for extreme (maximum / minimum) values in array A (for example array
A is the array you want to sort) and exchange 3 with the first index, then
isolate the first index.
b. Then determine the next extreme value and exchange with the second
index, then isolate the second index.
c. Repeat these steps until the last data.

Following is an example of sorting (ascending) with the selection method :

0 1 2 3 4 5 Index
3 7 2 1 6 5 Array A (initial value)

1 7 2 3 6 5 Find the minimum from the 0-5 index then exchange


with the 0th index

1 2 7 3 6 5 Find the minimum from 1-5 index then exchange with 1st
index

Find the minimum from 2-5 index then exchange


1 2 3 7 6 5
with 2nd index

Laboratorium Dasar Komputer Telkom University 41


Find the minimum from 3-5 index then exchange
1 2 3 5 6 7
with 3rd index.

Find the minimum from 4-5 index then exchange with


1 2 3 5 6 7
4th index

C Algorithm
#include <stdio.h> Program selectionSort
int a[100];
Dictionary :a : array [1..100] of
int i,j,n,min,temp;
main () integer
printf("How many data that you have : "); i, j, n, min, temp : integer
scanf("%d",&n); Algorithm :
for (i=0;i<=n-1;i++)
Output(‘Input a lot of data : ‘)
{
printf("Data to-%d : ",i+1); Input(n)
scanf("%d",&a[i]); i traversal [1..n]
} Output(‘Input the data to-‘,i,’ : ‘)
//selection sort process
Input(ai)
for (i=0;i<=n-2;i++)
{ i traversal [1..n-1]
min=i; min  i
for (j=i;j<=n-1;j++) j traversal [i+1..n]
if (a[j]<a[min])
if (aj < amin) then
min=j;
temp=a[min]; min  j
a[min]=a[i]; temp  amin
a[i]=temp; amin := ai
}
ai := temp
//displays the sorting result
for (i=0;i<=n-1;i++) i traversal [1..n]
{ Output(ai,’ ‘)
printf("%d",a[i]);
printf(" ");
}
}

Laboratorium Dasar Komputer Telkom University 42


3. Insertion sort
The working principle of insertion sort is to sort the numbers that have been
read and the next will repeatedly insert numbers in an unread array to the left
of the sorted array. The ordering process starts from the second index.
The following is an example of sorting using insertion sort :
0 1 2 3 4 5 Index
5 3 4 7 6 1 Array A (initial value)

The data at index one is compared to the gray area. Because 3 <5 we need to
insert a second data in the gray area so that after the insertion, the gray portion
remains in a relatively ordered state, as follows::

C Algorithm
#include<stdio.h> Program insertionSort
int a[100];
int i,j,n,temp; Dictionary :
main () a : array [1..100] of integer
{ i, j, n, temp : integer

Laboratorium Dasar Komputer Telkom University 43


printf("numbers of data :"); Algorithm :
scanf("%d",&n);
Output(‘Insert number of data : ‘)
for (i=0;i<=n-1;i++)
{ Input(n)
printf("Data number-%d : ",i+1); i traversal [1..n]
scanf("%d",&a[i]); Output(‘Data number-‘,i,’ : ‘)
}
Input(ai)
// Insertion sort process
for (i=0;i<=n-1;i++) i traversal [2..n]
{ temp  ai
temp=a[i]; ji
j=i;
while ((j>1) and (temp < aj-1)) do
while ((j>0) && (temp<a[j-1]))
{ aj  aj-1
a[j]=a[j-1]; jj-1
j=j-1; aj  temp
}
i traversal [1..n]
a[j]=temp;
} Output(ai,’ ‘)
//sorting result
for (i=0;i<=n-1;i++)
{
printf("%d",a[i]);
printf(" ");
}
}

4. Bubble sort
The working principle of bubble sort is to compare a data (data to i) with data
next to it (data to i + 1), exchange the two data if the data is greater than the
data next to it (ascending sorting)
The following is an example of sorting using the bubble sort method:

0 1 2 3 4 5 Index
5 3 7 1 6 4 Array A (initial value)

a. Compare the first data with the second data, because 5> 3 then exchange
the two data. Followed by comparing the first and second data, because 5
<7 there is no exchange. and so on until the data to n (6)

3 5 1 6 4 7

b. Compare the first data with the second data, then the second data with the
third data, and so on until the data to n-1 (5)

Laboratorium Dasar Komputer Telkom University 44


3 1 5 4 6 7

c. Repeat the process until the data is sorted

1 3 4 5 6 7
1 3 4 5 6 7
1 3 4 5 6 7

C Algorithm

#include <stdio.h> Program bubbleSort


int a[100];
int i,j,n,temp;
main() Kamus : :
{
printf("A lot of data : "); a : array [1..100] of integer
scanf("%d",&n); i, j, n, temp : integer
for (i=0;i<=n-1;i++)
{ Algoritma :
printf("Data to-%d : ",i+1); Output(‘Input a lot of data : ‘)
scanf("%d",&a[i]); Input(n)
}
i traversal [1..n]
//bubble sort process
for (i=n-1;i>=1;i--) Output(‘Input data to-‘,i,’ : ‘);
for (j=1;j<=i;j++) Input(ai)
{ i traversal [n..2]
if (a[j-1]>a[j]) j traversal [2..i]
{
temp=a[j-1]; if(aj-1 > aj) then
a[j-1]=a[j]; temp  aj-1
a[j]=temp; aj-1  aj
} aj  temp
}
//displays the sorting result i traversal [1..n]
for (i=0;i<=n-1;i++) Output(ai,’ ‘)
{
printf("%d",a[i]);
printf(" ");
}
}

Laboratorium Dasar Komputer Telkom University 45


MODULE 8 : SEARCHING

Practicum Aim
1. Understand the logic of searching by using methods
sequensiall and binary.
2. Able to implement search logic into the program using C language.

The search algorithm is the process of searching for a particular element or value in
a data set. There are two kinds of search methods.
1. Sequential Search
Sequential search is the simplest search method, where searches are done in
sequence, from the first data to find the search data. Data are compared one at a time
from the beginning until the data is found or not found.
Suppose there is a data in array A: 5 3 1 8 4, and what is sought is number 1, the
program will check the data at each index one by one and the data will be found at
index 3.
C Algorithm
#include<stdio.h> Program sequentialSearch
Int a[100];
Int i,n,find; Dictionary :
main () a : array [1..100] of integer
{
printf("The amount of data : "); i, n, cari : integer
scanf("%d",&n); Algorithm :
for (i=0;i<=n-1;i++)
{ Output(‘The amount of data: ‘)
printf("Data %d :",i+1); Input(n)
scanf("%d",&a[i]);
i traversal [1..n]
}
printf("Searched data: "); Output(Data ‘,i,’ : ‘)
scanf("%d",&find); Input(ai)
Output(‘Searched data: ‘)
// sequential search process
i=0; Input(find)
while ((i<=n-1) && (a[i]!=find)) i  1
i=i+1;
if (a[i]==find) while (i ≤ n) and (ai≠find) do
printf("Data found in index: %d i  i + 1;
",i+1); if(ai = find) then
elseprintf("Data not found");
} Output(‘Data found in index: ‘,i)
else
Output(‘Data not found’)

Laboratorium Dasar Komputer Telkom University 46


2. Binary Search
This method can only be done on a data set that has been sorted beforehand.
If there are N data in array A, the data to be searched will be compared with data
A [mid], where mid is the middle index of array A (low = 1, high = N, mid = (high
+ low) div 2 or ( 1 + N) div 2). Assume the data is sorted in ascending order:
❖ if the data A [mid] is greater than the data sought it will be narrowed in
the search area (low value becomes mid + 1)
❖ if the data A [mid] is smaller than the data sought it will be narrowed in
the search area (high value becomes mid - 1)

The following is an example of a binary search :

low = mid = (0+5) div high


0 2 =5

low mid = hig


0= 11 2 (1+6)
3 div4 5 h =Index
1 3 10 152 17 20 6 Array A already sorted

Suppose the data you want to search is 17, because A [mid] <> search then the
search area will be narrowed down. Because A [mid] <find, the low value
changes to mid + 1 = 3 and the mid value becomes (low + high) div 2 = (3 + 5)
div 2 = 4

low mid high

0 1 2 3 4 5 Index
1 3 10 15 17 20 Array A

If the data you want to find is 3, then the high value will change to mid - 1 = 2
and the mid value to (low + high) div 2 = (1 + 2) div 2 = 1
low mid hig
h
low = high
0mid 1 2 3 high4 5 Index
1 3 10 15 17 20 Array A

Laboratorium Dasar Komputer Telkom University 47


The search will continue until the data is found or the value of mid = low = high
but the data has not been found.
C Algorithm
#include <stdio.h> Program binarySearch
int a[100]; Dictionary :
int i,n,search,idx,low,high, mid; a : array [1..100] of integer
main () i, n, cari, idx, low, high, mid :
{
printf("how much data : "); integer
scanf("%d",&n); Algorithm :
for (i=1;i<=n;i++)
{ Output(‘how much data : ‘)
printf(“data %d : ",i); Input(n)
scanf("%d",&a[i]); i traversal [1..n]
} Output(‘data ‘,i,’ : ‘)
printf("searched data : ");
scanf("%d",&search); Input(ai)
Output(‘serached data : ‘)
//sort the data first Input(search)
//fill this space by sorting method { -------------------- }
{ -- sorting process -- }
// binary search process
low=0; { -------------------- }
high=n+1; low  1
idx=0; high  n
while ((low<=high) && (idx==0))
idx  0
{
mid=(low+high)/2; while (low ≤ high) and (idx = 0) do
if (a[mid]==serach) mid  (low + high) div 2
idx=mid; if(amid = search) then
else if (a[mid]<search)
idx  mid
low=mid+1;
else high=mid-1; else if(amid < search) then
} low  mid + 1
if (idx!=n+1) else high  mid - 1
printf("Data found in index : if(idx ≠ 0) then
%d",idx+1);
else printf("Data not found"); Output(‘Data found in index : ‘,i)
} else
Output(‘Data not found)

Remember that array index started from zero! But in array algorithm started from
first index

Laboratorium Dasar Komputer Telkom University 48


MODULE 9 : RECURSIVE ALGORITHM
Practicum Aim
1. Able to understand the working principle of a recursive algorithm.
2. Able to understand the use of basis and recurrences on the recursive algorithm
3. Able to implement the recursive algorithm as a substitute of an iterative
algorithm on a simple program.

Basic Theory :

Recursion is a algorithm. make a call to himself. Algorithms that are recursion


are called recursive. Recursion can only be used in procedures and functions, this is
because only procedures and functions can be called. In general, recursion can be
illustrated as an iterative algorithm but using functions and procedures. In recursion
there are two important terms, namely basis and recurrences. First, bases are
conditions that will stop the recursive process. While recurrences are commands that
will call the recursive algorithm itself (in this case the procedure or function).
The following is an example of using a recursive algorithm to find factorial
values.
#include <stdio.h> Basis → the circumstances that will
cause the recursive process to stop →
int nFactorial(int n);
int x, result; n = 0 or n = 1

int main(){ Recurrence → the circumstances that


printf("FACTORIAL FUNCTION\n"); will cause the recursive process to
printf("Please input a number: ");
scanf("%d", &x); getchar(); continue by calling to the algorithm
result = nFactorial(x); itself → nFactorial(n-1);
printf("Factorial result: %d",
result); Assume that the input n = 3, then
return 0;
}
int nFactorial(int n){ nFactorial = 3 * nFactorial(2)
if (n==1 || n==0){ nFactorial = 2 * nFactorial(1)
return 1; nFactorial = 1 * nFactorial(0)
} else if (n>1) {
nFactorial = 1
return n * nFactorial(n-1);
}
} Thus, nFactorial = 3 * 2 * 1 * 1 = 66

In addition, the following is another example of using recursive algorithms.

Laboratorium Dasar Komputer Telkom University 49


Input Students Data Prime Number Checker
#include <stdio.h> #include <stdio.h>
struct student{ int checkprime(int p);
char name[20], id[20]; int n;
} std; int main(){
printf(" Input a number : ");
int n; scanf("%d", &n); getchar();
void input(int x);
if (n > 1){
int main(){ int p = checkprime(n-1);
printf("Total student : "); if (p == 1){
scanf("%d", &n); getchar(); printf("%d is a prime number\n",
input(n); n);
} else {
return 0; printf("%d is not a prime
} number\n", n);
}
void input(int x){ } else {
if (x > 0){ printf("%d is not a prime
printf("Name : "); number\n", n);
gets(std.name); }
printf("ID : ");
gets(std.id); return 0;
}
x = x - 1;
input(x); int checkprime(int p){
} if (p == 1){
} return 1;
void print(int x){ } else if (n%p == 0) {
if(x > 0){ return 0;
printf("\nName: %s", } else {
student[x].name); return checkprime(p-1);
printf("\nID : %s", }
student[x].id); }
x--;
print(x);
}
}

Laboratorium Dasar Komputer Telkom University 50


MODULE 10 : FILE HANDLING

Practicum Aim
1. Understanding file forms in the algorithm.
2. Understanding data storage by using text files and binary files.
3. Can distinguish between text files and binary files.
4. Can open files, open files, open data to files, and read them for both binary text
and binary files in the algorithm as well as in C language.

General Description :

File handling is used so that the results of an executable program can be stored
permanently in any storage device, not 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, the FILE structure (often referred to as a file
handle) and declared in the standard stdio.h header file. The structure will store a file's
current flow information which includes a file position indicator, a buffer pointer (if
any), an error indicator that saves when a read/write error occurs, an end-of-file
indicator that stores when the end of a file has been achieved, as well as other
information needed.
The first way must be done to get information from the structure
The FILE is declaring a pointer that will point to the FILE structure. Such a pointer
is called a file pointer. Following are the general form of pointer declaration 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, so the syntax for writing is as follows.
Stages of File Operations
Operations on the file include three main stages.
1. Open / activate the file
2. Processing files
3. Close the file

Laboratorium Dasar Komputer Telkom University 51


1. Open / activate the file
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 are the basic forms.

FILE *fopen (const char * restrict filename, const char * restrict


mode);
Description
❖ filename, in the form of the name of the file (string), to be opened.
var contohfile : text;
❖ mode, which is a type of operation (string) to be performed on a file
❖ Then, the basic form in this module is contained in the file stdio.h.
❖ The function will return a pointer that points to the object (FILE) to control the data
flow of a file. If the file opening operation fails, fopen returns a NULL pointer (a null
pointer constant that is defined based on the implementation of a platform).
Mode Meaning

“r” Open the file for the reading process. If the file does not yet exist, the
file will fail to open. Meanwhile, if the file exists, then the file can be
read with the file position indicator initially positioned at the
beginning of the file.
“r+” Same as "r", but can also be used for the writing process.

“w” Open the file for the writing process. If the file does not yet exist, the
file will be created. Meanwhile, if the file does not yet exist, then all
the contents of the file will be deleted without any prior warning.
Finally, if the file is successfully opened, then the file can be written
with the file position indicator initially positioned at the beginning of
the file.
“w+” Same as "w", but can also be used for the reading process

“a” Open the file for the appending process. If the file does not yet exist,
the file will be created. Meanwhile, if a file exists, it will cause the
process of writing data to the file to be written at the end of a file,
despite the intervention of the file positioning function (will be
discussed later in this module). Finally, if the file is successfully
opened, the file position indicator will initially be positioned based on
the implementation of a platform whether at the beginning or the
end of the file..
“a+” Same as "a", but can also be used for the reading process.

Laboratorium Dasar Komputer Telkom University 52


For example, here is an example of using the Fopen function.

fp = fopen (“TES.TXT”, “w”);

Notes:
❖ If the mode argument has a ‘+’ symbol in it, It is referred to as the update

mode. The process of input (reading from a file) and output (writing to file) can be
implemented in the current flow of a file in question.
❖ The writing process should not be directly followed by the writing process

without any intervening fflush function call or 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.

2. Processing Files
When a file is opened, the file can be treated as a binary file or text file. Binary files
are files 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 data of type or string type. Meanwhile, binary files
are usually used to store complex data, such as structures
What can be done to work with binary files is to add additional characters, namely
"b" to the mode argument of the fopen function. Meanwhile, working with text files
does not require adding characters.

❖ Text file,
With r, w, a or update mode with r +, w +, a +

❖ Binary file,
With rb, wb, ab or update mode with rb +, wb +, ab +, or r + b, w + b, a + b.

A. TEXT FILES
1. Writing and Reading String Data in Text Files
To write data strings to a file, remember that the printf function is used to write to
the screen, while the fprintf function can be used to write to a file. Next, to read the
string data in the file, there is a function called fgets. Here is the basic form.

Laboratorium Dasar Komputer Telkom University 53


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

Description
❖ s is a data string
❖ stream is a FILE pointer
❖ n defines how many characters will be stored on the string s.
❖ Print The fprintf function is used to write the string s into a file based on the
string pointed to by the format to determine the arguments (...) which will then be
converted to output in the file. This function will return the number of characters
written, or a negative value if the output or error encoding process in the file occurs.
❖ The fgets function is used to read strings from file into 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 it will return the
string s.
Write String Data into Text File Read String Data from Text File
#include <stdio.h> #include <stdio.h>
char string[255]; char string[255];
int main(){ int main(){
FILE *f_text; FILE *f_text;
f_text= fopen("example.txt", f_text = fopen("example.txt", "r");
"w"); while (fgets(string, sizeof(string),
gets(string); f_text) != NULL)
fprintf(f_text, "%s\n", printf("%s", string);
string);
fclose(f_text); fclose (f_text);
return 0; return 0;
} }
For the record, the format argument used in the fprintf function, which is "% s \
n" has a newline character in it. The new line character must be written manually into
the file, without it, instead of making a text file that consists of more than one line
correctly, the file will be written in only one line.

Besides using the fgets function, fgetc can also be used to read string data. The
difference is that fgets are used to read on a string basis, whereas fgetc is used to

Laboratorium Dasar Komputer Telkom University 54


read on a character basis (remember that a string is a collection of characters, in other
words, an array of char). Here are the basic forms.

int fgetc(FILE *stream);


The fgets function takes characters from files of type unsigned char (has a range
of 0 - 255 values in the ASCII value) which are then converted to positive int values.
The function returns the character of the file pointed to by the stream. If a reading
error occurs, it will return EOF.

Reading String Data from a Text File Using fgetc


#include <stdio.h>
int character;
int main(){
FILE *f_text;
f_text = fopen("example.txt", "r");
while( (character=fgetc(f_text)) != EOF)
printf("%c", character);
fclose(f_text);
return 0;
}

EOF is an int negative constant that is defined based on the implementation of


a platform, this value is usually returned by several functions such as fgetc to
indicate the end of a file, in other words, no data can be read from the character.
Therefore, to read correctly using fgetc, don't declare a backup variable to store
the character as char, but declare it with int.

2. Append data to Text File


The method for adding data to a file is almost the same as for writing data. The
difference is in the file mode argument in the fopen function that is being opened by
the file. It's simple, change the "w" or "w +" file to "a" or "a +" to add.
Add String Data to a Text File

Laboratorium Dasar Komputer Telkom University 55


#include <stdio.h>
char string[255];
int main() {
FILE *f_text;
f_text = fopen("example.txt", "a");
gets(string);
fprintf(f_text, "%s\n", string);
fclose(f_text);
return 0;
}

B. BINARY FILE
1. Writing and Reading Data in Binary Files
There are two functions for writing or reading a data in the form of memory blocks
(consisting of bytes), for example to write any data type such as float or struct. These
two functions are called fread and fwrite. Here are the basic forms.

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 an area of memory that will be used as a

temporary data storage for reading from files (for fread) or for writing data into
files (for fwrite).

❖ size The size of one memory block in bytes to be read or written.

❖ nmemb adds the number of memory blocks to be read or written at one time.

❖ stream is a file pointer that points to FILE.

❖ _T 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 a sizeof operator.

❖ Both functions return the sum of the number of memory blocks that have been
read (for fread) or written (for fwrite) at one time.

Laboratorium Dasar Komputer Telkom University 56


❖ To be able to write or read data for more than one memory block (based on the
value of nmemb), an array must be used as a temporary storage place as an input
to the ptr argument..

Write Data to Binary File Read Data From Binary File


#include <stdio.h> #include <stdio.h>
int main(){ int main(){
FILE *f_structure; FILE *f_structure;
int n, i;
struct { struct {
char Menu[30]; char Menu[30];
double Price; double Price;
} list; } list;

f_structure=fopen("Price List.dat", f_structure=fopen("Price


"wb"); List.dat", "rb");
printf("Please input the amount of
menu: "); while(fread(&list,sizeof(list),1,
scanf("%d", &n); getchar(); f_structure)==1){
for (i=1; i<=n ;i++){ printf("Menu:%s \n",list.Menu);
printf("Menu : "); printf("Harga:%lf\n",list.Price);
gets(list.Menu); }
printf("Price : ");
scanf("%lf",&list.Price); fclose(f_structure);
getchar(); return 0;
fwrite(&list,sizeof(list),1, }
f_structure);
}

fclose(f_structure);
return 0;
}
Note
In this example, a file with the name "Price List" will have the extension ".dat",
please note that any extension (including .txt) can be used for both text and binary
files.
2. Add Data to the Binary File
The method for adding data to a binary file is almost the same as the method for
writing data. Of course, use the "wb", "wb +", or "w + b" files to write and "ab", "ab +",
or "a + b" to add.

Append Data to Binary File

Laboratorium Dasar Komputer Telkom University 57


#include <stdio.h>
int main(){
FILE *f_structure;
int n, i;
struct {
char Menu[30];
double Price;
} list;
f_structure = fopen("Price List.dat", "ab");

printf("Please input the amount of the new additional


menu: ");
scanf("%d", &n); getchar();

for (i=1; i<=n; i++){


printf("Menu : "); gets(list.Menu);
printf("Price : "); scanf("%lf", &list.Price);
getchar();

fwrite(&list, sizeof(list), 1, f_structure);


}

fclose(f_structure);
return 0;
}

Laboratorium Dasar Komputer Telkom University 58


3. Access Binary Files Randomly

C language provides facilities that make it possible to read and write files
randomly by changing the file position indicator. With this facility, for example, that
a data in the middle of a file will 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 is the basic form.
int fseek(FILE *stream, long int offset, int whence);

Description
❖ If the operation fails, it returns a value other than zero that is defined based on

the implementation of the platform.


❖ stream is a file pointer that points to FILE

❖ offset is the value of the byte adjustment to the whence reference.

❖ whence is the file position indicator reference.

❖ Remember, after a successful fseek call, the next operation in the update data

stream can be input (read from file) or output (write to file)

Here is a table of whence references.


Macro File Location Reference
SEEK_SET On Set location file
SEEK_CUR On Current location file
SEEK_END On End location file
These macros are defined based on the implementation of a platform which is an
integer constant with different values.

Example :
1. fseek(fp, 3, SEEK_SET); The file position indicator will be changed
3 bytes after the beginning of the file.

2. fseek(fp, -3, SEEK_END); The file position indicator will be changed


Perhatikan tanda negatif. 3 bytes before the end of the file.

3. fseek(fp, 3, SEEK_CUR); The file position indicator will be changed


3 bytes after the current file position
indicator.

Laboratorium Dasar Komputer Telkom University 59


4. fseek(fp, -sizeof(DATA), SEEK_CUR); The file position indicator will be changed
Perhatikan tanda negatif. based on the size of the DATA object
before the current file position indicator.

Keep in mind that the offset argument can also accept negative values.

Extra, the rewind function

void rewind(FILE *stream);

Description
❖ Rew The rewind function changes the file position indicator for the data stream
pointed to by the stream to the beginning of the file. This is the same as (void)
fseek (stream, 0L, SEEK_SET) except the error indicator in the data stream is also
deleted. Rew The rewind function does not return a value.

Following is an example of using the fseek function.


Accessing Binary File Randomly
#include <stdio.h>
int main(){
FILE *f_structure;
int struct_number;
long int byte_offset;

struct {
char Menu[30];
dobule Price;
} list;

f_structure = fopen("Price List.dat", "rb");


printf("Please input the desired number order of menu in the
list: "); File position indicator
scanf("%d", &struct_number); getchar(); will be positioned
just before the data
which will be printed
byte_offset = (struct_number - 1) * sizeof(list); into the screen later.
fseek(f_structure, byte_offset, SEEK_SET);

if (fread(&list, sizeof(list), 1, f_structure) == 0){


printf("The associated menu can’t be found on the list.\n");
} else {
printf("Menu : %s\n", list.Menu);
printf("Price : %lf\n", list.Price);

Laboratorium Dasar Komputer Telkom University 60


}

fclose(f_structure);
return 0;
}

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

Assuming that the file will be opened in "rb" mode, the file position indicator is first
positioned at the beginning of the file. If the third data will be read, fseek (fp, 2 *
sizeof (DATA), SEEK_SET) can be called. fseek will position it right before the third
data.
7 8 9 10 8
proses fread
Thus, the fread function will read the third data correctly.

4. Erasing Data in Binary Files


There are several ways to properly remove data. But only one will be explained in
this module. Here is the proper procedure to do it.

1. Open the main file in read mode


2. Create a temporary file and open it in write mode
3. Copy all of the data from the main file into the temporary file, except the data which
will be removed
4. Close the main file and the temporary file
5. Remove the main file
6. Rename the temporary file based on the main file name
7. Remove the temporary file.

The C language also provide the functions to remove and rename a file, respectively
named remove and rename. Here is the prototype of them.

int remove(const char *filename);


var contohfile : text;

Laboratorium Dasar Komputer Telkom University 61


The remove function causes the file whose name is the string pointed to by filename to
be no longer accessible by that name. In other words, the file will be gone.

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

The rename function causes the file whose name is the string pointed to by old to be
henceforth known by the name given by the string pointed to by new.

The remove and rename function returns zero integer if the operation succeeds and
nonzero platform implementation defined value if it fails.

Remove Data on Binary File


#include <stdio.h>
#include <string.h>
int main(){
FILE *f_structure;
FILE *f_structure2;

char toFind[50];

struct {
char Menu[30];
double Price;
} list;

f_structure = fopen("Price List.dat", "rb");


f_structure2 =fopen("Price List2.dat", "wb");

printf("Please input the name of menu which will be removed: ");


gets(toFind);

while (fread(&list, sizeof(list), 1, f_structure) == 1){


if (strcmp(list.Menu, toFind) != 0){
fwrite(&list, sizeof(list), 1, f_structure2);
}
}

fclose(f_structure);
fclose(f_structure2);
remove("Price List.dat");
rename("Price List2.dat", "Price List.dat");

return 0;
}

Laboratorium Dasar Komputer Telkom University 62


3. Close file
To close a file, there is a function called fclose. The general form is as follows.

int fclose(FILE *stream);


Description
❖ stream is a file pointer that points to FILE

❖ If the fclose function is successful, it will eliminate the data flow file pointed to

by the stream and close the file in question. Data buffer for the writing process
that has not been written in the data stream will be written first, but the data buffer
for the unread reading process will be discarded.
❖ The fclose function returns zero if the data flow was successfully closed, or EOF

if an error was detected.

ADDITION
Emptying the Buffer in the Data Flow
int fflush(FILE *stream);

Description
❖ stream is a file pointer that points to FILE.

❖ Buffer Data buffer for the writing process that has not been written into the flow

of a data will be written first


❖ if the last operation is not input (reading from a file), the fflush function will

cause the data buffer for the writing process that has not been written in the flow
of the data to be immediately written into the file. In addition, the behavior of this
function is undefined.
❖ F The fflush function will set an error indicator for the data flow and return the

EOF value if a writing error occurs. Otherwise it will return zero value..

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

❖ fpos_t is a data type that can store information needed to uniquely determine

each position in a file.

Laboratorium Dasar Komputer Telkom University 63


❖ Get fgetpos will store the file position indicator in the object pointed to by the
post and fsetpos will change the file position indicator based on the value of the
object pointed to by the post.
❖ Both of these functions will return zero integers if the operation is successful

and otherwise defined based on the implementation of a platform if it fails.

Laboratorium Dasar Komputer Telkom University 64


MODULE 11 : BASIC TECHNIC ON WRITING REPORT

Practicum Aim
1. Understand the use of M.S Word in making Reports
2. Create Table of Contents, Bibliography, and Automatic Caption
3. Can use Formating 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 relate to the responsibility given to the person
concerned. This fact contains a statement or information obtained from observations
or experiences by the person given responsibility. In making reports, a basic technical
understanding is needed in the use of document creation applications such as M.S.
Office. Here are some basic techniques that need to be understood when preparing a
report.

1. Margin

Margin is the distance between the typing edge and


the edge of the paper page. The usual margin used
in making reports is (4-3-3-3) cm in the order (Left -
Right-Top-Bottom).

To adjust margins, Layout → Margin → Custom


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

Laboratorium Dasar Komputer Telkom University 65


2. Multilevel List

Multilevel List is multilevel writing


numbering which is set automatically, so
numbering with lower level will be more
multilevel

At Home menu choose Paragraph- →


Multilevel List → Heading List

3. Style Modify
Style Modify is useful for modifying the writing format of chapter titles,
sections, captions, and writing in paragraphs. 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 done (For Normal Text formatting styles).

Laboratorium Dasar Komputer Telkom University 66


• For heading 1, heading 2, adjust as
needed. Heading 1 is usually intended for
Level 1 format (REFERENCES, TABLE OF
CONTENTS, CHAPTER 1) for heading 2
(format level 2) intended for sub-chapters
such as (1.1, 2.2).
• • Styles in Heading 1 & Heading 2,
changed to Bold, Times New Roman, size 12,
color Black

4. Style Header
In giving chapter and sub-chapter headings, use Style Heading 1 and Style Heading 2.
Usage: click on the text you want to format, then click Heading 1 or Heading 2. After
the text changes, a Navigation Pane (Can be seen in the view menu) will appear that
will show the part that uses Heading 1 or Heading 2.

Laboratorium Dasar Komputer Telkom University 67


5. Caption
Caption is useful as a description or explanation that accompanies illustrations in the
form of pictures or tables. To use caption select the Reference menu → Insert
Caption → New Label → Write ‘Image’.

To insert Numbering in Caption. Reference → Caption → Numbering → Format (1,2,3)


→ check the Include chapter number → Chapter starts with style Heading 1 → Use
Separator periode.

Then use it in the picture. Right-click on the image → Insert Caption → Pilih
Gambar → Below selected item → Ok then give the image title. For a list of tables,
right click on the table → Insert Caption → Select Table if there is a table label
→ Position Above selected item.
6. Page Numbering
To give a page number, click on the footer (the bottom of the page) 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, image list), use
the roman numeric format.

Laboratorium Dasar Komputer Telkom University 68


7. Table of Contents, Images and Tables Automatic.
1. To display the Table of Contents automatically, select the menu Reference → Table of
Contents → Custom table of Contents → Ok.

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

Laboratorium Dasar Komputer Telkom University 69


BIBLIOGRAPHY

• Anon., 2019. Functions in the C programming Language. [Online] Available at:


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

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


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

• Kadir, A., 2012. Algoritma & Pemrograman Menggunakan C & C++. Yogyakarta:
Penerbit Andi Offset.

• Kernighan, B. W. & Ritchie, D. M., 1988. The C Programming Language. Murray


Hill, New Jersey: AT&T Bell Laboratories.

• 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-
differencesbetween-a-pointer-variable-and-a-reference-variable-in

• Schildt, H., 2003. C++:The Complete Reference,Fourth Edition. Osborne: McGraw-


Hill.

Laboratorium Dasar Komputer Telkom University 70

You might also like