Professional Documents
Culture Documents
JZMH aXKBJ3TwcVIkazQwapfCMfeHvtqxB xBJ1Y
JZMH aXKBJ3TwcVIkazQwapfCMfeHvtqxB xBJ1Y
JZMH aXKBJ3TwcVIkazQwapfCMfeHvtqxB xBJ1Y
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.
Compiler Team
I the undersigned
NIP : 14890058
Hereby declare that all the information in this module has been reviewed and will be used
as the main course material supplement for the practicum that will be held on the first
semester of 2021/2022 term at Laboratorium Dasar Komputer, School of Electrical
Engineering, Telkom University.
Husneni Mukhtar, S.Si, M.T., Ph.D Dr. Rahmat Awaludin Salam, S.Si., M.Si.
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:
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.
The following are the Rules for the Implementation of Practicum Activities for the Odd
Semester of the 2023/2024 Academic Year.
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
Approved, Aware,
Laboratory and Studio Basic Computing Laboratory
Head of Affairs, Assistant Coordinator,
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
Assistant
No NIM Assistant Name Contact ID Line
Code
1 1102210135 Abdillah Nur Isnaini ABD 085254648494 abdillah729
IDE
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.
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.
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.
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
• 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.
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.
or
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
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.
Off-Page State the connection from the process to the other process
Connector on a different page.
Pre-defined State the other procedures that have been made in the
Process diagram.
Circumference = 2x(length+
width)
Display the
circumference of
the
End
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 :
// main
function
main(){
/*statemen */
}
// other function
Other_function(){
/* statemen */
}
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.
Program Example :
a. Display Sentences
#include <stdio.h>
int main ()
{
printf (“Hello World \n”);
return 0;
}
C Algoritma
a=7; a7
C Algoritma
• "\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.
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
Format
Practicum Aim
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
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.
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.
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;
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
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.
Practicum Aim
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.
Description :
Note :
Conversely, if used to reduce the value of a variable it is called decrement, for example:
i-- or - i.
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.
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.
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
}
}
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
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
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
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;
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 */
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);
}
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.
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.
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]);
}
}
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
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
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.
0 1 2 3 4 5 Index
3 7 2 1 6 5 Array A (initial value)
1 2 7 3 6 5 Find the minimum from 1-5 index then exchange with 1st
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(" ");
}
}
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
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)
1 3 4 5 6 7
1 3 4 5 6 7
1 3 4 5 6 7
C Algorithm
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’)
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
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
Remember that array index started from zero! But in array algorithm started from
first index
Basic Theory :
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
“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.
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.
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
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).
❖ nmemb adds the number of memory blocks to be read or written at one time.
❖ _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.
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.
fclose(f_structure);
return 0;
}
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
❖ Remember, after a successful fseek call, the next operation in the update data
Example :
1. fseek(fp, 3, SEEK_SET); The file position indicator will be changed
3 bytes after the beginning of the file.
Keep in mind that the offset argument can also accept negative values.
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.
struct {
char Menu[30];
dobule Price;
} list;
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.
The C language also provide the functions to remove and rename a file, respectively
named remove and rename. Here is the prototype of them.
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.
char toFind[50];
struct {
char Menu[30];
double Price;
} list;
fclose(f_structure);
fclose(f_structure2);
remove("Price List.dat");
rename("Price List2.dat", "Price List.dat");
return 0;
}
❖ 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
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
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..
Description
❖ stream is a file pointer that points to FILE.
❖ fpos_t is a data type that can store information needed to uniquely determine
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
1. Margin
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).
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.
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.
2. To display a List of Figures and Tables, select the menu Reference → Insert Table of
Figures → Custom table of Contents → Ok.
• Kadir, A., 2012. Algoritma & Pemrograman Menggunakan C & C++. Yogyakarta:
Penerbit Andi Offset.
• 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