Structure of Programming Algorithms (SPA)

In an algorithm, the problem-solving steps can be in the form of a sequence structure, a selection structure, and a repetition structure. These three types of steps form the construction of an algorithm.

Basic Structure of Programming Algorithms

Substance:

  1. SEQUENCE STRUCTURE
  2. RECTANGLE AREA ALGORITHM
  3. TUBE FILLING ALGORITHM
  4. SELECTION STRUCTURE OR CONDITIONAL SELECTION
  5. SIMPLE IF
  6. STUDENT GRADUATION ALGORITHM 1
  7. IF ... THEN ... ELSE ...
  8. STUDENT GRADUATION ALGORITHM 2
  9. SALARY PAYMENT ALGORITHM
  10. NESTED IF
  11. VALUE CONFERENCE ALGORITHM
  12. REPETITION STRUCTURE
  13. STRUCTURE FOR
  14. FOR NUMBER PRINTING ALGORITHM
  15. ALGORITHM FOR PRINTING EVEN NUMBERS FOR
  16. WHILE STRUCTURE
  17. WHILE NUMBER PRINTING ALGORITHM
  18. ALGORITHM FOR PRINTING EVEN NUMBERS WHILE
  19. DO...WHILE STRUCTURE
  20. ALGORITHM FOR PRINTING NUMBERS DO ... WHILE
  21. ALGORITHM FOR PRINTING EVEN NUMBERS DO ... WHILE

1. Sequence Structure

A sequential structure is a program structure where each line of the program will be executed sequentially from top to bottom according to the order in which it is written.

Sequence Structure

From the flowchart above, the processor will first execute the program line 1 instruction, the program line 2 instruction will be executed if the program line 1 instruction has been completed. Furthermore, the program line 3 instruction is executed after the program line 2 instruction has been completed. After the program line 3 instruction has been completed, the algorithm stops. Example:

2. Rectangle Area Algorithm

To calculate the area of ​​a rectangle whose length and width are known, the algorithm is as follows:

Given a rectangle that has length and width.

Structure Description:

  1. start
  2. Read long
  3. Read wide
  4. Calculate area = length * width
  5. Show area
  6. finished

Flowchart Area_of_Rectangle:

Flowchart Area_of_Rectangle

3. Tube Filling Algorithm

The volume of a cylinder will be calculated if the radius of the circle and the height of the cylinder are known.

Cylinder 1
Given a cylinder with a known radius and height.

Structure Description:

  1. start
  2. Read the fingers
  3. Read high
  4. Calculate area_of_circle = 3.14 * radius * radius
  5. Calculate the volume of the cylinder = area of ​​the circumference * height
  6. Show tube_contents
  7. finished.

Flowchart of Tube_Fill1:

Flowchart Fill_Cylinder1

Note that the Isi_Tabung1 algorithm above has 5 lines of instructions that must be executed before the algorithm is complete. The algorithm above can be simplified further so that the process lines are fewer.

Cylinder 2
A cylinder is known with a known radius and height.

Structure Description:

  1. start
  2. Read the fingers
  3. Read high
  4. Calculate the volume of the cylinder = (3.14 * radius * radius) * height
  5. Show tube_contents
  6. finished

Flowchart Fill_Cylinder2

From the two algorithms and flowcharts above, it can be seen that the second algorithm has fewer instruction lines, causing the processing to be completed faster with the same results as the first algorithm. In the second algorithm, if implemented in a program, the variable requirements are also fewer, saving memory usage.

4. Selection Structure / Selection Conditions

In the selection structure, not every line of the program will be executed. Only the program lines that meet the requirements are executed. The selection structure is a program structure that performs a testing process to make a decision whether a line or block of instructions will be processed or not. This condition testing is done to select one of several available alternatives.

In programming, selection is done on a boolean statement, which can produce a true or false value. Usually a selection statement consists of operands connected by relational operators and combined with logical operators.

Example:

  • 7 = 7 (Value true, because 7 is the same as 7)
  • 5 = 9 (Wrong value, because 5 is not the same as 9)
  • 4 > 2 (Values ​​true, because 4 is greater than 2)
  • 3 <> 8 (Values ​​true, because 3 is not the same as 8)
  • X = 10 (Can be true or false, depending on the contents of the X variable)
  • (X > 3) And (Y < 12) (Can be true or false, depending on the contents of the variables X and Y) The selection structure in program writing is implemented with the IF instruction.

The IF structure has several types, including:

5. Simple IF

Simple IF form pseudocode

IF <syarat> THEN
<instruksi>

Flowchart form:

Flowchart form:

In this simple IF form, the instruction will be executed if the condition being tested is true. If the condition being tested is false, no instruction will be executed.

Example-1:

6. Student Graduation Algorithm 1

It is known that a student is said to have passed if his/her score is >= 60.

Structure Description:

  1. start
  2. Read student_grades
  3. If student_score >= 60 then do step 4
  4. Print "The student passed"
  5. finished

Student Graduation Flowchart_1:

Student Graduation Flowchart_1

From the flowchart above, it can be explained that after the student's score is entered, it will be tested whether the student's score is greater than or equal to 60? If true, it will print "The student passed" then finished, if not then finished.

7. IF … THEN … ELSE …

General form of pseudocode:

IF <syarat> THEN
<instruksi1>
ELSE
<instruksi2>

In this form, there are two possible choices that will be executed based on the test results, if the tested condition is true then instruction 1 is executed, and if the tested condition is false then instruction 2 is executed.

Flowchart form:

Flowchart form

8. Student Graduation Algorithm 2

A rule is made for a student's graduation which is known from the results of his/her grades in the form of numbers. A student is said to have passed if the grade is greater than or equal to 60, and if the grade is less than 60 then the student does not pass.

It is known that a student is said to have passed if his/her score is >= 60, and if his/her score is <60 then the student has not passed.

Structure Description:

  1. start
  2. Read student_grades
  3. If student_score >= 60 then do step 4, otherwise do step 5
  4. Print "The student passed"
  5. Print "Student failed"
  6. finished

Student Graduation Flowchart_2:

Student Graduation Flowchart_2

From the flowchart above, it can be explained that after the student's score is entered, it will be tested whether the student's score is greater than or equal to 60? If true, it will print "The student passed" then finished, if not, it will print "The student did not pass" then finished.

Example 2:

9. Salary Payment Algorithm

Create an algorithm and flowchart to calculate the amount of salary payment with input name, number of working days and number of overtime hours. The rate for working days is Rp. 30,000,- per day, while the rate per hour of overtime is Rp. 5,000,-. If an employee's overtime hours are more than 10 hours, they will get additional overtime transportation of 10% of the amount of overtime pay, otherwise they will not get overtime transportation.

Given the input data name, number of working days and number of overtime hours, the rate per working day is IDR 30,000, the rate per overtime hour is IDR 5,000, if the number of overtime hours is more than 10 hours then you will get an additional overtime transportation money of 10% of the amount of overtime money.

Structure Description:

  1. start
  2. Read the name
  3. Read jhr_kerja
  4. Read overtime hours
  5. Calculate wages = work_hr * 30000
  6. Calculate overtime pay = overtime hours * 5000
  7. If jjam_lebur > 10 then do step 8 otherwise do step 9
  8. Calculate overtime = (10/100) * overtime pay
  9. trans_overtime = 0
  10. Calculate salary = wages + overtime pay + overtime transfer
  11. Show salary
  12. finished

Salary Payment Flowchart:

Salary Payment Flowchart:

From the flowchart above, it can be explained that after the name, workday, overtime hours are entered, the amount of wages will be calculated, then the amount of overtime pay will be calculated, then tested whether the overtime hours > 10, if correct then the overtime pay is calculated as 10% of the overtime pay, if wrong then the overtime pay = 0, then the amount of salary obtained is calculated. Finally, it is printed in the form of name and salary, then finished.

10. NESTED IF

General form of pseudocode:

IF <syarat1> THEN
<instruksi1>
ELSE IF <syarat2> THEN
<instruksi2>
ELSE IF <syarat3> THEN
<instruksi3>
ELSE IF <syaratm> THEN
<instruksim>
ELSE
<Instruksin>

Flowchart form:

Flowchart form

In this form there are many possible choices that will be carried out based on the test results, the testing process is:

If the condition1 being tested is true then instruction1 is executed, if the condition1 being tested is false then condition2 is tested, if condition2 is true then instruction2 is executed, if condition2 is false then condition3 is tested, if condition3 is true then instruction3 is executed, if condition3 is false then conditionm is tested, if conditionm is true then instructionm is executed, and so on, if no conditions are met then instructionm is executed.

Example:

11. Value Conversion Algorithm

Create an algorithm and flowchart to calculate student grade conversion, input in the form of student names and grades in the form of numeric grades. The final result is in the form of letter grades from the conversion with the following rules:

  1. If the numeric value >= 80 then the letter grade is the same as A
  2. If the numeric value >= 70 then the letter grade is the same as B
  3. If the numeric value >= 60 then the letter grade is equal to C
  4. If the numeric value >= 50 then the letter value is equal to D
  5. If the numeric_value < 50 then the letter value is equal to E

It is known that a student's numerical value will be converted to a letter grade.

Structure Description:

  1. start
  2. Read student_name
  3. Read numeric_value
  4. If the number_value >= 80 then the letter_value = "A", otherwise
  5. if numeric_value >= 70 then letter_value = "B", otherwise
  6. if numeric_value >= 60 then letter_value = "C", otherwise
  7. if numeric_value >= 50 then letter_value = "D", otherwise
  8. letter_value = "E"
  9. Print student_name and letter_grade
  10. finished

Value_Conversion Flowchart:

Value_Conversion Flowchart

In this nested IF form, what needs to be noted is that if a condition has been met, then the other conditions below it will not be tested again. In the example above, for example, the inputted numeric value is 75, then the letter value is B (see the flowchart form), so the test is not continued for the conditions below it. In other words, the input numeric value of 75 will not be tested for whether the numeric value >= 60, whether the numeric value >= 50 or whether the numeric value < 50.

12. REPETITION STRUCTURE

A repetition structure is a structure that repeats one line or one block of program lines several times according to the given requirements.

Repetition structures have several forms:

13. STRUCTURE FOR

The loop structure with the for instruction is used to repeat a line of instructions or a block of instructions until the required number of repetitions is met. The main characteristic of the for loop is that there is a start value and an end value that indicate the number of repetitions to be performed.

Flowchart structure for:

Flowchart structure for

From the flowchart image above, it can be explained that instruction1, instruction2, instruction3 will be executed repeatedly starting from the initial value to the final value given. If the repetition has reached the final value condition given, the repetition will stop.

Example 1:

14. ALGORITHM FOR PRINTING NUMBERS FOR

The numbers 1 to 10 will be printed using the for loop.

Prints numbers 1 to 10 with a for loop.

Structure Description:

  1. start
  2. do step 3 starting from i = 1 to i = 10
  3. print i
  4. finished

Flowchart Print_Numbers with for:

Flowchart Print_Numbers with for

From the flowchart image above, it can be explained that the first i value will contain 1, then the i value is printed, in the for loop the value of the i variable will increase automatically so that the current i variable value becomes 2, then the i value is printed, and so on until the i value contains 10, then the loop process is complete.

Example 2:

15. ALGORITHM FOR PRINTING EVEN NUMBERS FOR

It will print even numbers starting from 0 with the end limit entered from the keyboard using a for loop.

Prints even numbers with an end limit entered using for.

Structure Description:

  1. start
  2. Read end_limit
  3. Do steps 4 to 5 starting from i = 1 to i = final_limit
  4. If i is divisible by 2 then do step 5
  5. print i
  6. finished

Flowchart to print even numbers with for:

Flowchart to print even numbers with for:

From the flowchart image above, it can be explained that the first time the loop end_limit is read, then the value of i will first contain 1, then it will be tested whether the value of i is divisible by two, if true then the value of i is printed, then the loop is continued with the value of i becoming 2, if not then the loop will be continued with the value of i becoming 2, and so on until the value of i is greater than the end_limit.

16. WHILE STRUCTURE

The loop structure with the while instruction is used to repeat one line of instructions or one block of lines of instructions as long as the given condition is still met. The main characteristic of the while loop is that the condition will be tested first before the instruction to be repeated is executed, in other words, in the while instruction the condition will be tested in advance, so there is a possibility that the line of instructions to be repeated will not be executed at all (the condition is not fulfilled).

Flowchart of while structure:

Flowchart of while structure:

From the image above, it can be explained that the condition will be tested first before entering the repeated block. If the condition being tested is true then instruction1, instruction2, instruction3 will be executed, after executing instruction1, instruction2, instruction3 then the condition will be tested again. If the condition being tested is true then instruction1, instruction2, instruction3 will be executed again, the repetition will stop if the condition being tested is false.

Example:

17. WHILE NUMBER PRINTING ALGORITHM

The example above will be made using while. The numbers 1 to 10 are printed with the while loop.

Description:

  1. start
  2. i = 1
  3. as long as i <= 10 do steps 4 to 5
  4. print i
  5. i = i + 1
  6. finished

Print_Numbers Flowchart:

From the flowchart image above, it can be explained that the first time i has a value of 1, then it is tested whether i is less than or equal to 10, if true then the value of i is printed, then the value of i is increased by 1, then the value of i is tested again whether it is still less than or equal to 10 if true then the value of i is printed, and so on. The loop will stop if the value of i is greater than 10.

18. ALGORITHM FOR PRINTING EVEN NUMBERS WHILE

The example above will be made using while. Even numbers are printed with a deadline entered using while.

Structure Description:

  1. start
  2. Read end_limit
  3. i = 1
  4. as long as i <= limit_end do steps 5 to step 7
  5. If i is divisible by 2, do step 6
  6. print i
  7. i = i + 1
  8. finished

Flowchart Print_Even_Numbers:

Flowchart Print_Even_Numbers:

From the flowchart image above, it can be explained that the first time the limit_end of the loop is read, then i is given a value of 1, then it is tested whether i is smaller or equal to the limit_end, if true then it is tested whether the value of i is divisible by 2, if true then the value of i is printed, then the value of i is increased by 1 so that the value of i becomes 2, if not then the value of i is immediately increased by 1 so that the value of i becomes 2, then the value of i is tested again whether it is still smaller or equal to the limit_end if true then it is tested whether the value of i is divisible by 2, if true then the value of i is printed, then the value of i is increased by 1 to 3, if not then the value of i is immediately increased by 1 to 2, and so on until the value of i is greater than the limit_end so that the loop ends.

19. DO ... WHILE STRUCTURE

The loop structure with the do...while instruction is used to repeat one line of instructions or one block of lines of instructions until the condition is not met. The main characteristic of the do...while loop is that the condition will be tested after the instruction to be repeated is executed, in other words, in the do...while instruction, the condition will be tested behind, so that the line of instructions included in the do...while block will be executed at least once.

Flowchart of do...while structure:

Flowchart of do...while structure:

From the image above, it can be explained that instruction1, instruction2, instruction3 will be executed first, then the condition is tested. If the condition being tested is true, then instruction1, instruction2, instruction3 will be executed again, after that the condition is tested again, the loop will stop if the condition being tested is false.

Example:

20. ALGORITHM FOR PRINTING NUMBERS DO ... WHILE

The example above will be made using do...while. The numbers 1 to 10 are printed with the while loop.

Structure Description:

  1. start
  2. i = 0
  3. i = i + 1
  4. print i
  5. if i < 10 do steps 3 to 4
  6. finished

Print_Numbers Flowchart:

Flowchart Print_Numbers

From the flowchart image above, it can be explained that the first time i is given an initial value of 0, then the value of i is increased by 1 so that the value of i becomes 1, then the value of i is printed. After printing, the value of i is tested whether i is less than or equal to 10, if true then the value of i is increased by 1, so that i becomes 2, then the value of i is printed. After that, the value of i is tested again whether i is less than or equal to 10, and so on until the value of i is greater than 10 then the loop will stop.

Example :

21. ALGORITHM FOR PRINTING EVEN NUMBERS DO ... WHILE

The example above will be made using do...while. Even numbers with a deadline are printed by using do..while.

Structure Description:

  1. start
  2. Read end_limit
  3. i = 1
  4. As long as i <= end_limit do steps 5 to 7
  5. If i is divisible by 2, do step 6
  6. print i
  7. i = i + 1
  8. finished

Flowchart Print_Even_Numbers:

Flowchart Print_Even_Numbers:

From the flowchart image above, it can be explained that the first time the limit_end of the loop is read, then i is given an initial value of 1, after that it is tested whether the value is divisible by 2, if true then print the value of i, then the value of i is increased by 1 so that i becomes 2, if not then the value of i is immediately increased by 1, so that the value of i becomes 2. After testing whether the value of i is smaller or equal to the limit_end, if true then it is tested again after that it is tested whether the value is divisible by 2, if true then print the value of i, then the value of i is increased by 1 so that i becomes 3, if not then the value of i is immediately increased by 1, so that the value of i becomes 3. After testing whether the value of i is smaller or equal to the limit_end, and so on until the value of i is greater than the limit_end so that the loop is complete.

Source - © STMIK El Rahma Yogyakarta. Compiled by Mr. Eko Riswanto, ST, M.Cs.

Programming Algorithm Structure Other Versions

An algorithm is a sequence of logical steps for solving a problem that is arranged systematically. The problem can be anything, with the note that for each problem, there are initial conditions that must be met before running the algorithm. The concept of an algorithm is often equated with a recipe. A recipe usually has a list of ingredients or spices to be used, the order of work and how the results of the order of work are. If the ingredients used are not listed (not available) then the recipe cannot be worked on. Likewise, if the order of work is irregular, then the expected results cannot be obtained.

Different algorithms can be applied to a problem with the same conditions. The complexity of an algorithm is a measure of how much computation the algorithm requires to solve the problem. Generally, algorithms that can solve a problem in a short time have a low complexity, while algorithms that take a long time to solve a problem require a high complexity.

Consider the following simple algorithm.

Example 5.10. Algorithm to calculate the area of ​​a triangle

  1. Start
  2. Read the base and height data.
  3. The area is the base times the height times 0.5
  4. Show Area
  5. Stop

The algorithm above is a very simple algorithm, there are only five steps. In this algorithm there is no repetition or selection. All steps are done only once.

At first glance the algorithm above is correct, but if observed carefully, this algorithm contains a fundamental error, namely there is no restriction on the data values ​​for the base and height. What if the base or height data value is 0 or a negative number? Of course the results that come out are not as expected. In cases like this we need to add steps to ensure that the base and height values ​​meet the requirements, for example by checking the incoming input. If the input base and height values ​​are less than 0, the program will not be run. So the algorithm above can be changed to the following example.

Example 5.11. Results of improvements to the triangle area calculation algorithm

  1. Start
  2. Read the base and height data.
  3. Check the base and height data, if the base and height data values ​​are greater than zero then proceed to step 4, if not then stop.
  4. The area is the base times the height times 0.5
  5. Show Area
  6. Stop

From the explanation above, we can draw the main conclusions about the algorithm. First, the algorithm must be correct. Second, the algorithm must stop, and after stopping, the algorithm gives the correct result.

1. How to Write an Algorithm

There are three ways of writing algorithms, namely:

Structured English (SE)

SE is a pretty good tool to describe an algorithm. The basis of SE is English, but we can modify it with Indonesian so that we can call it Structured Indonesian (SI). Algorithms such as in Examples 5.10 and 5.11 are algorithms written using SI. Because the basis is everyday language, SE or SI is more appropriate to describe an algorithm that will be communicated to software users.

Pseudocode

Pseudocode is similar to SE. Because of this similarity, SE and Pseudocode are sometimes considered the same. Pseudo means imitation or copy or resemble, while code refers to program code. So pseudocode is code that is similar to the actual program code instructions. Pseudocode is based on real programming languages ​​such as BASIC, FORTRAN or PASCAL. Pseudocode based on the PASCAL language is a pseudocode that is often used. Sometimes people call pseudocode a PASCAL-LIKE algorithm. If Example 5.10 is written in BASIC-based pseudocode, it will look like Example 5.12.

Example 5.12. Pseudocode

  1. Start
  2. READ base, height
  3. Area = 0.5 * base * height
  4. PRINT Wide
  5. Stop
  6. Start
  7. READ base, height
  8. Area = 0.5 * base * height
  9. PRINT Wide
  10. Stop

In Example 5.12, it appears that the algorithm is very similar to the BASIC language. Statements such as READ and PRINT are keywords in the BASIC language that replace the words "read data" and "display" respectively. By using pseudocode as above, the process of translating the algorithm into program code becomes easier.

Flow chart

Flowchart or flow chart is a scheme/chart that shows the flow in a program logically. Flowchart is a tool that is widely used to describe algorithms in the form of certain notations. In more detail this section will be discussed in the next section.

In the flowchart there are several important symbols used to create algorithms as shown in Figure 5.3.

This notation is called Terminator
This notation is called Terminator which means it is used to indicate the beginning and end of an algorithm.

This notation is called Data
This notation is called Data which is used to represent input or output data or to state data entry operations and printing results.

process notation
This notation is called Process which is used to represent a process.

decision notation
This notation is called Decision which is used for a selection, selecting conditions in a program.

preparation notation
This notation is called Preparation which is used to give an initial value, final value, addition/subtraction for a counter variable.

This notation is called Predefined Process
This notation is called Predefined Process which is used to indicate an operation whose details are shown elsewhere (procedure, sub-procedure, function)

connector notation
This notation is called Connector which is used to show the connection of a flowchart that is broken on the same page or the next page.

arrow notation
This notation is called Arrow which is used to show data flow or data flow from one process to another.

Program Flowchart can consist of two types, namely program logic flowchart and detailed computer program flowchart. Program logic flowchart is used to describe each step in a computer program logically and is usually prepared by a system analyst. While detailed computer program flowchart is used to describe computer program instructions in detail and is usually prepared by a programmer. If Example 5.10 is made into a flowchart program, it will appear in Figure 5.4.

Figure 5.4. Program flowchart
Figure 5.4. Program flowchart

2. Sequential Algorithm Structure

Sequential Algorithm Structure

There are three basic structures used in creating algorithms, namely sequencing structures, selection/decision/branching structures and looping structures. An algorithm will usually combine these three structures to solve a problem.

In this section we will first discuss the structure of the sequential algorithm. The sequential structure can be likened to a car traveling on a straight path with no intersections as shown in Figure 5.5. The car will pass kilometer after kilometer of road until it reaches its destination.

A sequential structure consists of one or more instructions. Each instruction is executed sequentially according to the order in which it is written, that is, an instruction is executed after the previous instruction has finished executing. The order of instructions determines the final state of the algorithm. If the order is changed, the final result may also change. According to Goldshlager and Lister (1988) sequential structures follow the following provisions:

  1. each instruction is executed one by one
  2. each instruction is executed exactly once, nothing is repeated
  3. the sequence of instructions executed by the processor is the same as the sequence of actions as written in the algorithm
  4. the end of the last instruction is the end of the algorithm.

Example 5.13. Flowchart to calculate the area of ​​a shape

Make a flowchart to calculate:

  • a. volume of the cuboid
  • b. area of ​​a circle

Solution :

This problem is a problem with a sequential structure algorithm because there is no selection or repetition process. For the volume of a block, we must determine the input and output variables needed. To calculate the volume of a block, the input variables are length, width and height. While the output variable is volume. In the area of ​​a circle, the input variable is radius and the output variable is area. To calculate the area of ​​this circle, we also need the constant phi. The flowchart for these two problems can be seen in Figure 5.6.

Example 5.14. Flowchart for temperature conversion.

Create a flowchart to convert temperature in Fahrenheit to temperature in Celsius using the formula oC = 5/9 x (oF -32).

Solution :

This problem also still uses an algorithm with a sequential structure. The input variable required is F and the output variable is C. The flowchart for these two problems can be seen in Figure 5.7.

Figure 5.6. Flowchart for calculating the volume of a cuboid and the area of ​​a circle.
Figure  5.6. Flowchart for calculating the volume of a cuboid and the area of ​​a circle_

3. Branching Algorithm Structure

A program will not always run by following a sequential structure, sometimes we need to change the order of program execution and want the program execution to jump to a certain line. This event is sometimes called a branch/selection or decision. This is like when a car is at an intersection as in Figure 5.7. The driver must decide whether to take the right or left lane.

Figure 5.8. Car at an intersection

In a branching structure, the program will change the order of execution if a required condition is met. In this process, the Decision flowchart symbol must be used. The decision symbol will contain a statement that will be tested for truth. The test result value will determine which branch will be taken.

Example 5.15. Branching structure for the age limit problem.

A rule for watching a particular movie is as follows, if the age of the viewer is more than 17 years old then the viewer is allowed and if less than 17 years old then the viewer is not allowed to watch. Make a flowchart for the problem.

Solution :

The above problem is a characteristic of a problem that uses a branching structure. This is marked by the presence of the statement if .. then ... (or If ... Then in English.

The problem solving flowchart is shown in Figure 5.9. In the figure, the use of the Decision symbol is shown. In this symbol, a condition check occurs, namely whether the age is over 17 years or not. If the answer is yes, the program will produce the text output "Please Watch", while if the age input is less than 17 years, the program will produce the text output "You May Not Watch".

Figure 5.9. Flowchart for solving movie watching problems.
Figure 5.9. Flowchart for solving movie watching problems.

Example 5.16. Branching structure for calculating two numbers.

In a calculation, the value of P = X + Y. If P is positive, then Q = X * Y, while if it is negative, then the value of Q = X/Y. Make a flowchart to find the value of P and Q.

Solution:

In this example, the inputs required are the values ​​of X and Y, while the condition checking process is carried out on the value of P whether it is positive (including 0) or negative. Observe the problem solving flowchart in Figure 5.10.

Figure 5.10. Flowchart for solving the calculation of two numbers.
Figure 5.10. Flowchart for solving the calculation of two numbers.

The two examples above (5.15 and 5.16) are examples of simple branching structures involving only one branch. In more complex problems, we will encounter more branches. We will also encounter a branching structure that is inside another branching structure, or what is commonly called nested. Consider the following examples.

Example 5.17. Nested branching structure for the photocopy problem

A photocopying business has the following rules:

  • If the photocopying status is a subscriber, then no matter how many sheets he photocopies, the price per sheet is Rp. 75,-
  • if the photocopy is not a subscription, then if he photocopies less than 100 sheets the price per sheet is Rp. 100,-. While if more than or equal to 100 sheets then the price per sheet is Rp. 85,-.

Create a flowchart to calculate the total price to be paid if someone photocopies X number of sheets.

Solution:

In this example, the problem looks more complicated. There are two branches that occur. The first is checking whether someone's status is a customer or not. Second, if someone's status is not a customer, then a check is carried out on how many sheets of photocopies, whether more than 100 sheets or not.

In this question we also encounter what is called nested. Note the statement in the second condition of the problem above.

If the person who photocopies is not a regular customer, then if he photocopies less than 100 sheets, the price per sheet is IDR 100.

The second if statement is inside the first if. The inputs needed for this problem are the status of the person who photocopied and the number of sheets photocopied. So the input variables used are:

  • Status for the status of the person who photocopied
  • JLF for the number of sheets photocopied

In addition, there is a variable named HPP which is used to store the price per sheet and TH to store the total price value. Note, the Status variable is of char data type, so it must be written using the " " sign.

The flowchart for solving this problem can be seen in Figure 5.11.

Figure 5.11. Flowchart for solving photocopying problems
Figure 5.11. Flowchart for solving photocopying problems

Example 5.18. Nested branching structure for student graduation problem

The student graduation rules for the Web Programming subject are applied as follows:

  • If the mid-semester exam (UTS) score is greater than 70 then the student is declared to have passed and the Final Score is the same as the UTS score.
  • If the UTS score is less than or equal to 70, then the student is declared to have passed if the Final Score is greater than or equal to 60 where the Final Score = (UTS score x 40%) + (UAS score x 60%).

Make a flowchart for solving the problem if the desired output is NIM, Student Name, Final Grade and Graduation Status.

Solution:

In this example, there are two branches. The first is checking whether the student's mid-term test score is more than 70. Second, if the mid-term test score is not more than 70, then a check is carried out whether the final score is more than 60.

The inputs needed for this problem are NIM, student name, mid-term exam score, and final exam score. So the input variables used are: NIM for student ID number, name for student name, NUTS for mid-term exam score, and NUAS for final semester exam score. While the output variables consist of NA which is used to store the final score and Status to store the graduation status.

Figure 5.12. Flowchart of completion for student graduation.
Figure 5.12. Flowchart of completion for student graduation.

4. Repetition Algorithm Structure

Figure 5.13. Car racing on the circuit.
Figure 5.13. Car racing on the circuit.

In many cases, we are often faced with a number of tasks that must be repeated many times.

One example that we can easily find is a car race as shown in figure 5.13. The participating cars must circle the circuit track many times as determined in the race rules. Whoever reaches the finish line the fastest is the winner.

In making computer programs, we also sometimes have to repeat one or a group of commands many times to get the desired results. By using a computer, repeat execution is easy to do. This is because one of the advantages of computers compared to humans is their ability to do tasks or instructions repeatedly without feeling tired, bored, or lazy. Compare it with a race car driver, at some point he must feel tired and bored of going around in circles driving his race car.

The repetition structure consists of two parts:

  1. Loop condition , which is the condition that must be met to execute the loop. This condition is usually stated in a Boolean expression that must be tested whether it is true or false.
  2. Loop body , which is one or more instructions to be repeated.

In the loop structure, it is usually also accompanied by an initialization section and a termination section. Initialization is an instruction that is carried out before the loop is first executed. The initialization section is generally used to give an initial value to a variable. While termination is an instruction that is carried out after the loop is completed.

There are several forms of repetition that can be used, each with its own requirements and characteristics. Some forms can be used for the same case, but there are forms that are only suitable for certain cases. The choice of the form of repetition for a particular problem can affect the correctness of the algorithm. The choice of the right form of repetition depends on the problem to be programmed.

Loop structures with For

Looping using For is one of the oldest looping techniques in programming languages. Almost all programming languages ​​provide this method, although the syntax may differ. In the For structure, we must first know how many loop bodies will be repeated. This structure uses a variable commonly referred to as the loop's counter, whose value will increase or decrease during the looping process. A general flowchart for the For structure is shown in Figure 5.14. Note the use of the preparation symbol in the flowchart.

Figure 5.14. The structure of the iteration algorithm with For.
Figure 5.14. The structure of the iteration algorithm with For.

In executing a loop with For, the sequence of steps is as follows:

  1. Sets the counter value equal to the start.
  2. Checks whether the counter value is greater than the final value. If true then exit the repetition process. If the increase is negative, the process will check whether the counter value is smaller than the final value. If true then exit the repetition process.
  3. Executes the statements in the loop body
  4. Increase/decrease the counter value according to the amount specified in the increment argument. If the increment argument is not specified then by default the counter value will be increased by 1.
  5. Repeat from step no 2.

One important thing to note is that the counter value is always set at the beginning of the loop. If we try to change the final value in the body of the loop, it will not affect how many iterations will be performed.

Example 5.19. Algorithm to print a statement 100 times.

Maybe you have done something naughty in elementary school that made you write a certain statement 100 times as punishment for the naughty thing. For example, the statement that had to be written was "I will not repeat that act again". How does the algorithm work for this case?

Solution:

In this example, we need a counter variable, let's say we name it I. The initial value is 1 and the final value is 100. While the increment or increase each time iteration of I is one. The command to print the statement will be repeated one by one until the final value of the counter is met (100). The flowchart for solving this example can be seen in Figure 5.15.

Figure 5.15. Flowchart writing the statement 100 times.

Notice how easy it is to repeat. In Figure 5.15, the increment is not listed, because according to the steps explained previously, if it is not listed, the increment value is automatically one.

Example 5.20. Flowchart to print the members of a set.

Given a set A whose members are the numbers 1, 3, 5, .., 19. Make a flowchart to print the members of the set.

Solution:

In this example, we need a counter variable, let's say we name it A (according to the name of the set). The initial value is 1 and the final value is 19. From the set pattern we know that the increase in numbers is 2 (1 to 3, 3 to 5, and so on). So we can state that the increment or increase each time it is repeated from A is 2. The flowchart for solving this example can be seen in Figure 5.16.

Figure 5.16. Flowchart printing the members of a set.

In Figure 5.16, pay attention to the preparation symbol. There is an additional step 2 statement. This is called an increment. Each time it is repeated, the counter value, A, will increase by 2 so that what will be printed is 1, 3, 5, .., 19.

Example 5.21. Determining the outcome of a loop flowchart

Look at the flowchart in Figure 5.17. Determine the results of the flowchart.

Solution:

In this example, we are trying to determine the outcome of a flowchart. What do you think the answer is? Let's describe the flowchart process.

In the flowchart, after Start, we put a process that contains the statement A = 1. This part is called initialization. We give an initial value for A = 1. The counter variable is X with an initial value of 1 and a final value of 10, without an increment (or by default the increment is 1). When entering the loop body for the first time, the value of the variable A will be printed directly. The value of the variable A is still the same as 1. Then the next process is the statement A = A + 2. This statement may be a bit strange, but this is something programming. The meaning of this statement is to replace the old value of A with the result of adding the old value of A plus 2. So that A will be worth 3. Then the second repetition is carried out. In this condition the value of A is 3, so what is printed by the print command is 3. Only then do we replace the value of A with the addition of A + 2. The new value of A is 5. And so on. So that the output of this flowchart is 1, 3, 5, 7, .., 19.

Figure 5.17. Flowchart printing a specific number
Figure 5.17. Flowchart printing a specific number

We can see now that Figure 5.16 and 5.17 give the same output. Of the two flowcharts, Figure 5.17 is the recommended flowchart. Although longer, it is more structured. In addition, not all programming languages ​​provide increment setting facilities.

We must pay close attention to the flowchart in Figure 5.17, especially the position of the Print A statement. Try reversing its position so that the position of the A = A + 2 statement is above the Print A statement. What is the result? As with the branching structure, we will also encounter a form of nested repetition structure. This means that there is a repetition that is inside another repetition. Consider Example 5.22 below.

Example 5.21. Determining the outcome of a loop flowchart

Look at the flowchart in Figure 5.18. Determine the results of the flowchart.

Solution:

In this example, we try to determine the result of a flowchart with nested loops. What do you think the answer is? Let's describe the flowchart.

In Figure 5.18, there are two preparation symbols. The first one with the counter variable X and the second one with the counter variable Y. In terms of position, the counter variable Y is located after the counter variable X. This means that the repetition with the counter variable Y is located inside the counter variable X. This is what is called nested repetition.

In this form of repetition, the program execution flow will run as follows:

Figure 5.18. Flowchart with nested repetition
Figure 5.18. Flowchart with nested repetition

  1. The X variable will be filled with the initial value of the counter, namely 1.
  2. The Y variable will be filled with the initial value of the counter, namely 0.
  3. The Z value is calculated by multiplying X by Y. The value of X = 1 and the value of Y = 0 so the Z value = 0
  4. The X, Y and Z values ​​are printed on the screen.
  5. The flow rotates, and the Y value is increased to 1 while the X value is still one (because the X part has not rotated).
  6. The value of Z = 1 is the result of multiplying X = 1 and Y = 1.
  7. The X, Y, and Z values ​​will be printed again on the screen.
  8. The plot loops back so that the Y value becomes 2, so the Z value will become 2.
  9. After this the rotation will exit Y because the final value of the counter has been reached.
  10. The value of X will be increased by 1 to 2, and the process will repeat itself on the Y section as above.
  11. The iteration process is repeated continuously until the final value of the counter X, which is 3, is reached. So the final result of the flowchart is as follows:

loop example

From Example 5.21. above we can see that there are rules that must be met in nested repetitions, namely:

  • Each repetition (loop body) has its own counter variable.
  • These repetitions must not overlap.

Loop structure with While

In looping with For, the number of loops is known with certainty because the initial value (start) and the final value (end) are already determined at the beginning of the loop. What if we don't know for sure how many times to loop? Looping with While is the answer to this problem. Like For, the looping structure with While is also a structure that is supported by almost all programming languages ​​but with different syntax.

Figure 5.19. General flowchart While
Figure 5.19. General flowchart While

The While structure will repeat the statement in the loop body as long as the condition in While is true. In the sense that we do not need to know exactly how many times it is repeated. What is important is that as long as the condition in While is met, the statement in the loop body will be repeated. The general flowchart for the While structure can be seen in Figure 5.19.

In Figure 5.19., it appears that the preparation symbol for repetition as in For is no longer used. However, we use the decision symbol to control the repetition. In addition to conditions, usually in the While repetition, variable initialization must be done first.

Example 5.22. Looping with While to print a specific value.

Look at the flowchart in Figure 5.20. What is the output of the flowchart?

Solution:

Look at Figure 5.20. Can you determine the results of the lowchart? Pay attention to the following flowchart execution stages.

Figure 5.20. Flowchart of a loop with while to print a specific value.
Figure 5.20. Flowchart of a loop with while to print a specific value.

  1. In this flowchart, there are two variables that we use, namely A and B. Both variables are initialized to their initial values ​​(A = 1 and B = 0) before the loop process occurs. Variable A is a counter variable.
  2. In the decision symbol, the value of A will be checked whether it meets the condition (< 10). If Yes then the next command is executed, if not then the program will stop. At the beginning of this execution the condition will be met because the value of A = 1.
  3. Run the Print B command.
  4. The value of variable A is then replaced with the old value of A (1) plus 2. So the new value of variable A is 3. Meanwhile, the value of variable B = 9 (result of multiplying A = 3).
  5. The program will loop back to check whether the value of variable A is still less than 10. In this condition the value of A = 3, so the condition is still met. Then the steps repeat to step 3. And so on until the value of variable A no longer meets the requirement of less than 10. So the output of this flowchart is: 0, 9, 25, 49, 81.

As with For loops, While loops also allow nested loops. The rules and methods are the same as for For loops.

In some programming languages, repetition is also provided by Do ... Loop and Repeat .. Until. Both of these methods are similar to While, the difference is the location of the condition. In While, the condition check is placed before the loop body. While in Do ... Loop and Repeat ... Until, the condition check is done after the loop body.

Netizens

Some questions that were asked by visitors, when this site was still hosted by blogcepot:

  1. JEFRY DEWANGGA Apr 13, 2015, 08:34:00 = Most programming structures are described using flow charts, right? So it's easier to understand if it's described.
  2. SOPANDII ART Apr 20, 2015, 09:56:00 = Is there a program for adding array functions, bro? I still don't understand, thank you
  3. ANONYMOUS 16 Nov 2015, 10:44:00 = Bro, please post the difference between for next and for others. I'm still confused about the difference between the two, bro.
  4. ANONYMOUS 16 Nov 2015, 14:48:00 = there isn't one here, but I checked on another website and it said that for has 4 types: positive, negative, nested and for next, so I'm just confused about the difference between for next and the other fors.
  5. ANONYMOUS 16 Nov 2015, 15:47:00 = Oh ok bro, thanks for the info, I finally understand now (Y)
  6. WORLD BALLOON 3 Feb 2016, 13:01:00 = SUCCESS AND CONTINUOUS ACHIEVEMENTS
  7. BELAJARCODINGS.COM May 11, 2016, 06:40:00 = This is great  😃, the post can be a programming algorithm module. Thank you, Mas Wawan
  8. AHMAD_AZHAR Aug 1, 2016, 17:46:00 = I want to ask, sir, how is the algorithm for a program that uses procedures like a program for calculating geometric shapes. Thank you..
  9. KHABIB MUBARAK Nov 1, 2016, 19:57:00 = How is the description, flowchart and program .. adding N numbers, but only odd numbers are added. Please explain, bro
  10. KHABIB MUBARAK Nov 3, 2016, 19:45:00 = It was originally a question that turned into an assignment..hahaha Actually I've made one. But I'm not sure yet.. Just make a flowchart bro.. please help.. #add n numbers input, only odd numbers are added.. Thanks
  11. AZKAEXCEL 13 Jan 2017, 10:27:00 = Great explanation, bro. Permission to use as a reference and permission to share... Thanks for the info, this is what I need.
  12. ERIK WIBOWO May 22, 2017, 14:33:00 = very helpful thank you

And here is our response:

  1. That's right, Mr. Jefy Dewangga, so flow charts have many benefits, besides their main function as a framework, they are also useful for presenting a program system to the public, and can also help a programmer in troubleshooting or developing with reference to the flow chart.
  2. the concept is the same bro, use a loop to add array functions, just as mas SPANDII ART uses a loop to display the contents of an array,
  3. Hello Anonymous, sorry for next which one? because this post does not discuss for next, so I apologize, if you would please comment again on the related post, so we can answer it well and continuously.. thank you,
  4. Oh, actually "for" (during) is a representation of a loop, besides that, loops are not only "for" (during), but there is also "while", so Anonymous does not need to be confused, because the "for" loop is only one, there is no other "for" type of "for". As for what is meant by next, negative, positive, it is the name of the "variable" because the variable name is free, so there is no special standard for naming it, the program maker may give the variable a name, b, c, or an object name such as mouse, wheel, elephant, anu, etc. all of that depends on the context. So, in Anonymous' case, "for positive" is a special loop representation for positive number arithmetic, while "for negative" is for negative number arithmetic loops, while "for next" is a loop for the parameter of when to continue, so if written in the form of preposition logic language it becomes: "for positive" = "As long as the positive variable has this value (determined), then the program in one block {...} is executed" now, Anonymous can interpret the meaning of the other for - for himself. In order to understand more about loops and branches, please study the material in the "algorithm" & "c++" labels.
  5. Amen.. thank you
  6. ok, you are welcome, please
  7. Actually, you can use anything, for the first time learning I still apply the sequence structure like the instant noodle cooking algorithm. For example, a cube, then the first step is to prepare the necessary variables such as Length, Width, Height. Then from the three materials we can make a calculator for the Base Area or Volume like that.
  8. Hii KHABIB MUBARAK, your question may be short but the answer is not that short. Oh yeah, is that a question or an assignment? Hehehe, Please read and understand first, so that the questions asked are more specific. Thank you
  9. Hi AZKAEXCEL, please go ahead, I'd be happy to help. You're welcome.
  10. You're welcome, bro ERIK WIBOWO

Post a Comment

Previous Next

نموذج الاتصال