Transcripts
1. Welcome: Welcome to our course, how to learn programming with pseudocode. I'm Giannis Demertzidis and together, we will
learn step by step, how to solve simple and more complicated problems
with pseudocode. A little about my background. I hold a degree in Informatics and telecommunication
Engineering with over 12 years of experience in web development and over
9 years in photography. However, my true person lies in teaching coding, using pseudocode. Our goal is that by
end of the lessons, we will be able to write
pseudocode to solve problems. This knowledge will help us familiarize ourselves with
the mindset of programming. But why do we learn to write pseudocode before
starting programming? Converting a program written in pseudocode into any programming
language is simple. This is because the
only thing needed is learning the vocabulary of the programming language
we are interested in. But let's see how we will
gradually achieve this goal. Initially, we will talk about what a computer
understands in order to solve a problem for us by making a historical overview. Then we will see
what a problem is and how we think to
reach its solution. Once we understand the
mindset of problem solving, we will be able to move
on to writing pseudocode. We will discuss in
detail with examples the building blocks of
algorithms with pseudocode, as well as the slightly more
complex part of arrays. This way, we will gain the
knowledge needed to become familiar
with programming. Throughout this journey, we'll gradually
acquire knowledge that will help us solve problems using programs
written in pseudoode. One such problem to solve will be the assignment
for this course. Later on, after we have covered some basic concept
about pseudocode, we will see exactly what we need to do for
the assignment. In the end, I look forward to seeing your efforts
and your programs. However, let's not
delay any longer and start this journey into
the world of programming.
2. Introduction to Coding: In this first section,
we will provide an introduction to
define the algorithms. We've all heard the
concept of an algorithm. But what exactly is it? Simply an algorithm
is a series of instructions followed by a
computer to solve a problem. For example, the following algorithm converts
kilometers to miles. The user simply
inputs a value in kilometers and the algorith calculates and prints the result. In pseudocode, this
would be like this. If we wanted to give a
complete definition, it will be this. In order to call a series of
instructions an algorithm, it must meet the
criteria of input, output, definiteness,
finiteness, and effectiveness. Let's see what each
of these means. First of all, every algorithm
starts with an input. The definition we
see here means we need to provide the
algorithm with some values, which it will process to arrive at the solution
to the problem. At the end of every algorithm, there should be an output. The algorithm must
provide the result, which is the solution
to the problem. This result is either
printed out for the user or used as input
for another algorithm. Another characteristic
an algorithm should have is the definiteness. The instructions in an algorithm must be clear and obvious, leaving no room for doubt about how they
should be executed. We must consider all
possible scenarios that could affect the
flow of the algorithm. For example, a division
instruction must account for the case where
the divisor is zero. In addition, we should make sure that the algorithm we
write has finiteness. The algorithm must terminate after a finite number of steps. We cannot have an algorithm
that runs forever. For example, adding
positive numbers until the sum becomes zero or
negative cannot happen, so the algorithm would
never stop running. The last criterion
is effectiveness. Each instruction in an
algorithm must be simple. This means that an
instruction must not only be defined, but
also executable. This criterion is violated
in the following cases. Calculate the sum of all
prime numbers up to N, and then find the square
root of the result. The problem is that
this instruction is too complex and consists of
many successive actions, such as finding prime numbers, calculating the sum, and
extracting the square root. It is difficult to
execute directly and must be broken down into
similar instructions. Another instruction is,
find the average of the negative numbers in a set that contains no
negative numbers. The problem is that if the set contains no negative numbers, the instruction cannot
be executed as there are no negative numbers
to calculate the average. The instruction is not executable
under these conditions. As mentioned
earlier, the goal of every algorithm is
to solve a problem. However, the types of problems are not limited to
computing problems. They can also be other
problems in our daily lives. Why do we have computers
solve a problem in the first place instead
of solving it ourselves? It is certain that humans were solving problems long
before computers appeared and continue to do so even after the
development of technology. However, many times,
we choose to assign the computer to solve a problem instead of solving it ourselves. Why does this happen? First of all, computers execute instructions and operations
much faster than we do. Afterwards, computers handle repetitive
processes efficiently. For example, a typical
computer can perform calculations at the speed
of trillions per second. In addition, computers
can easily perform complex calculations that might be challenging for humans. Finally, we prefer computers
when the problem's data set is extensive as they can process large amounts of data
quickly and accurately.
3. How Computers Operate: Having introduced the
concept of algorithms and their contribution to problem solving in previous lessons, it's time to understand a
bit better how computers operate and how they execute
the commands we give them. The language that the computer understands is zero and one, known as machine language. With zero and one, we indicate whether current is flowing
or not, respectively. This is why the earliest
computers had switches. When they wanted to
command a computer to perform an operation
such as a calculation, they would "tweak" the appropriate switches to give the command. The first computer
ever built was vastly different from
the ones we used today. They were enormous in size, much slower in processing data, and their capabilities were
incomparably more limited. The main problem was that for each new operation they
wanted to perform, they had to reconfigure
the switches. This was a time
consuming process, especially since the
computer were entire rooms. With the advancement
of technology, the switches were replaced by other technologies
that were faster, more reliable, and
required less energy, such as vacuum
tubes, transistors, integrated circuits,
and later processors. However, remained the
problem that the only way to communicate with computers
was through machine language. The programmers of
the first computers had to know this
language very well, which created
significant issues. It was not
understandable to humans but was understandable
by the computer. The computers were
enormous whole rooms, and even for a small operation, a lot of work was required. Even if a program was
made on a computer, it would only work on that specific computer and and wouldn't be understandable
by another. To solve these problems, the low level language or
assembly language was created. This language was more
understandable by humans as it did not consist of
sequence of 0's and 1's, but used words like
ADD, etc. In Assembly language, words correspond to sequences
of 0's and 1's. Thus, a programmer could give commands to
the computer using specific words which the computer internally translated
into 0's and 1's, using a special program
called an Assembler. However, even these language failed to solve
fundamental problems. Programs still could not be transferred from one
computer to another. The programmer needed to have a deep understanding of the
computer's architecture. Programs in assembly language
were large and complex, making them difficult
to maintain. Next, came the high
level language, which appeared in the late 50s and solved the problem
of transferring a program from one computer to another. How was this done? Each computer internally used other procedures that
took the commands given in a high level
language like Java, and finally translated them
into machine language. Another advantage is that it is even more
understandable by humans. As it uses vocabulary
like Read and Write. Also, when another programmer
looks at a program, they can easily
understand what it does, and if necessary, correct it, making the maintenance
of the program easy. The only drawback is
that because there is this internal
translation process from a high level language to machine
language, it takes time. However, today,
computer speed is so high that this time
is insignificant. And there is no point in
writing in machine language. For example, we could write a program in machine
language in years, and it would be
directly executable, or we could write it in one
day in a high level language, and it would take 1
second to execute. Although writing in high
level language is easier, we also have to have
some basic experience in writing algorithms to
eventually write a program. In other words, creating
an algorithm or a program aims for those who have knowledge
in programming. To make this process more
accessible to non programmers, 4th generation
languages were created. An example is SQL for databases. Their function is that we "talk"
very simply to the program, and it gives us some
data. For example, "give me the names of students who scored above
10 in programming." To give such simple commands, one does not need
to be a programmer. However, what we
can request is more limited compared to writing a program in a high
level language. In conclusion, every
programming language has its strengths
and weaknesses. To the question "which could be considered the best
and most effective?", the answer is that
we cannot assert with certainty that one
programming language is objectively better
than the others because such a language
simply does not exist. There is no programming language convenient for all
types of problems. some may be suitable for
solving mathematical problems. other for business problems and other for
internet applications. For instance, if
someone wants to learn to create
websites without a CMS, they will learn PHP or
Python and not Java, as it serves a
different purpose. This raises the question, since all these languages
aim to create a program, why did we mention them
and how do they help us understand the concept of an algorithm? When
writing an algorithm, our goal is to be able to
write an equivalent program in any programming language that will solve a specific problem. The algorithm is written in a hypothetical language
called "pseudocode". Pseudocode follows all the basic principles
of programming, but it is a theoretical concept, and normally a program is written in
programming language. A programmer can take the solution to a
problem written in pseudocode and convert it into a high level language
to write the program. For someone new to programming, it is much easier to
understand pseudocode first, since they do not
need to learn much about its programming
laguage immediately. With pseudocode, we
become familiar with the way of thinking required
to write a program. And then by learning the vocabulary of the programming
laguage that suits us, we can create the
desired program.
4. Algorithms and Programs: Let's quickly go
over some concepts that will help us in the
continuation of the lessons. As we've already mentioned, an algorithm is a
theoretical concept. It refers to the thought process with follow to solve a problem. To practically represent
this thought process, we depict algorithms
in the following ways. Free text, Natural
Language step by step, Diagrammatic techniques,
and Coding. We will only use
coding, meaning, we will write a program in
pseudocode that when executed, will produce the same
results as the algorithm. Let's briefly look at what the other methods are
with a single example. In our example, we want to find the perimeter of a square. In free text, we would
write it as follows. Initially, we ask the user to provide the length of
one side of a square. Once we receive the side length, we keep it as a given for
the subsequent calculations. We multiply the side by 4, and the result of this operation is the perimeter of the square. Finally, we present
the result we found, i.e., the perimeter of the
square to the user. In natural language, we would
write it as follows. Start of algorithm, ask to find
out the length of the side. Take the side length,
multiply the side by 4. The result is the
perimeter of the square. Display the calculated
perimeter, End of algorithm. In a float chart, we would
depict it as follows. In coding, we would
write it as follows. We do coding when we want to write a program
or an algorithm. The difference
with algorithms is that coding is done in pseudocode. While in programs, it is done
in a programming language. And to better understand
the difference between an algorithm
and a program, let's look at some examples. This is an algorithm,
this is in Python, and this is in C#.
5. Problem Analysis: In the previous lessons, we introduced the concept of an
algorithm and pseudocode. Saw the difference
between pseudocode and programming and
emphasized why it is important to be
familiar with pseudocode before proceeding to learn
a programming language. In this chapter, we will see how we start
solving a problem. What the basic control
structure we use are. And what commands we use. At the same time, we
will begin to solve simple as well as
more complex problems by coding with pseudocode. As we mentioned in
our first lesson, the purpose of creating a
program is to solve a problem. However, before we look at the steps we need to
follow to achieve this, it is important to understand the concept of a
problem as a whole. This lesson has many
theoretical aspects. If we were to give a definition, we would say that the
problem is "a state of difficulty that
needs to be resolved." Problems have existed in
people's daily lives throughout the years of our history and can pertain to various fields
such as physics, mathematics, logic,
everyday life, etc. To address them, it
is necessary to fully understand all their
extensions and dimensions. This requires that the problem
is clearly articulated. If our code makes inappropriate
use of terminology and incorrect syntax can
create misunderstandings. That will distance us
from solving the problem. Even if verbal and syntax
rules are followed, there is a possibility of
misunderstanding the problem. Let's look at an example. Two friends Ben and Michael
are talking on the phone on a Friday morning to arrange
a time to go for a walk. Ben asks, "can you
make it Sunday morning or in the
afternoon at 6?" Michael replied that the
afternoon at 6 is better. However, the two friends did not meet, Ben waiting for
Michael that afternoon, but Michael did not
show up at the meeting. The appointment "in
the afternoon at 6" is open to double
interpretation. Ben meant the afternoon
of the same day, Friday at 6, while Michael meant Sunday
afternoon at 6. Therefore, we understand
how important it is for the proper formulation
of a problem to solve it. Having therefore
correctly formulated the problem we wish to solve, we then need to proceed
to record its structure. Here, we can see
the definition of the term structure of a problem. Thus, if we have a very
difficult problem, we break it down into sub
problems and then break down these sub problems into
smaller problems and so on. Until the solution to the
problems, is obvious. By solving these
simple problems, we have also solved
our original problem. Another important
requirement for solving a problem is to be able to
determine its requirements. In other words, the
data, -what we know-, and the objectives, -what we are looking for -,
must be identified. In some problems, this
can be easily understood, but there are also
some in which we must "discover" the data and objectives from the description
of the problem. In summary, let's
see the steps we follow to solve a
problem using a diagram. First, we must fully understand the problem and identify
its data and objectives. Next, we must
analyze the problem. To do this, we must
divide the problem into sub problems until their
solutions are obvious. Finally, we will arrive
at the solution to the original problem by
solving these sub problems.
6. Control Structures: Introduction: In the previous sections, we discussed what a program
written in Pseudocode is, its purpose, and how it help
us prepare for programming. We also covered
what we define as a problem and the stages
of problem solving. Based on this knowledge
and to move away from the theoretical
concept of algorithms and towards their
practical application, we will use our
online interpreter. This will help us
write Pseudocode in a hypothetical
programming laguage by creating our own programs. It is important to clarify
that normally a program is written in a programming
language and not in Pseudocode. The online interpreter is used
for educational purposes, and helps us become familiar with the thought
process of programming. All that's left for us to do to write a program is to learn the vocabulary of the
programming language we are interested
in, such as Python. Now we can dive into the practical aspects
and Control Structures. These structures are like "tools" that allow
the programmer to decide which parts
of the code will execute, when and how many times. If we learn this structure well, along with arrays that
we will cover later, we will be able to write any program in any
programming language we want. As the main difference is the vocabulary of that language. For better understanding, examples will be
given in each case, which we will solve
step by step together. Let's see what these
algorithm structures or Control Structures
in Pseudocode are. Sequence structure,
Selection structure, Multiple selection structure,
Nested procedures, and Repetition
structure or loops.
7. Control Structures: Sequence Structure: In the case where we
have a simple problem that is solved in a
specific sequence, we use the Sequence structure. For example, create a program
that reads 2 numbers, adds them and outputs their
sum in the PC screen. At this point, let's take a look at what our
main program does. First, it displays a message on the user's screen asking
them to input 2 numbers. Then it reads these
2 numbers and stores them in 2
variables, a and b. After that, it adds
them and assigns the result to a third
variable c. Finally, it displays a message
on the user's screen, followed by the result
of the addition. Before proceeding
to the explanation of the commands used
in this example, we need to clarify
certain concepts. The term "command"
refers to each word in the Pseudocode that corresponds
to a specific action. Each command is predefined in
every programming language, and we use it as it is, for example, to show the result of the
program in our Pseudocode we use the command PUBLISH and not SHOW ME, PRINT, etc. Other useful concepts are
the following. Constants, by this term, we refer
to predefined values that remain unchanged throughout the
execution of a program. Variables. A value
is assigned to the variable which can change during the
execution of the program. Depending on the type
of value they can take, variables are categorized
into indegers, reals, characters, and logical. Operators are known symbols used to perform various actions. Operators are categorized
into numerical, logical, also known as AND / OR
In our Pseudocode are expressed with AS_WELL_AS
and EITHER and comparative. An expression is a
sequence of operants, which are constants, and
variables and also operators. An expression can consist of just one variable or constant, up to a complex mathematical
representation. We use an assignment
statement in order to put the result of an
expression into a variable. Let's now analyze the program we previous wrote in detail. The first thing we need is to input the data into the program. To achieve this, using
the PUBLISH command, we ask the user to
provide us with the data. At this point, it's worth mentioning that whenever
we refer to PRINT, SHOW, DISPLAY or OUTPUT, it means the same thing, showing something to the user. This is done using the
PUBLISH command. Next, we use the word RETRIEVE and the name of one
or more variables. a , b etc. With this command, variable a will receive a numerical
value as its content. For example, if user
type 2 and 4, variable a will be 2, and
variable b, 4 respectively. In Pseudocode, when we use
the RETRIEVE command, it is synonymous
with read or input and means to read something
from the keyboard. Following this is an assignment statement
whose purpose is to perform operations and assign the result
to a variable. In our example, it takes
this form, but generally, it can be expressed as variable - assignment
statement - expression. Always on the left, we have the variable and right
the expression. This means to store
the result of the addition A and B
in variable C. Lastly, there is the PUBLISH command, which outputs, the result of the program on the PC screen. The program we have
just described meets all the criteria we mentioned earlier from the first lesson. The command RETRIEVE A
and B serves as input, and the command PUBLISH C serves as the output,
which is the result. Furthermore, it is characterized by definiteness,
defined commands, finiteness, a specific
number of commands, and effectiveness, clear
and simple commands. This problem may have
been very simple. But if we add a
few more commands such as the program name, the variables we will use, the start and end
statements of the program, we will have a complete
program that will run in our online
Pseudocode interpreter. We will gradually increase the difficulty until we
reach the sorting of arrays. Now let's look at
another example, a slightly more complex one. And this time, let's solve
it step by step together. The problem we have
is as follows. In a children's theater, tickets cost $20 for adults
and $15 for children. We need to write a
program that will accept the number of
adults and children who attended the performance and display the total
revenue of the theater. Firstly, to solve the problem, we need to find out what data we have and what we
are asked to find. The data we have is
that ticket for adults equals $20 and ticket
for children, $15. Also, we will ask the user
of the program to tell us how many adults and how many children
attended the theater. The objective is to
find the total revenue generated by the theater
from the performance. Before writing the commands
that address the problem, let's review the commands we said are necessary
for all programs. First, we give a
name to our program, using the command program_name. This name must always start with a letter and can contain
numbers or an underscore. But not symbols or
other punctuation marks. Next, we need to
define the variables. To indicate that variables
are coming next, we declare the
start of variables with a command, local_variables. And below that, we declare the variables with the
corresponding commands. For example, to declare
integer variables, we use local_integers. Note here that after the category commands
for the variables, the colon “:” symbol follows, whereas there is no colon in the command local_variables. Since we are at the
beginning of the program, we do not know yet
which integer variables we will need in our program. So we will write the
command local_integers and fill them in after we finish the pseudocode
for the main program. After the variable declaration, we proceed with the
start_operation command, which indicates the start of the Pseudocode for
the main program. Now let's write the main
Pseudocode and break down our initial problem
into sub problems. The first thing we need
to do is to find out how many adults and how many children
attended the theater. So in the program, we
would write is this. Publish, tell me how many adults and how many children
attended the theater, Retrieve adults, kids. The other problem we
need to solve is to calculate the total
revenue. To do this, we just need to first find
the total revenue from adult tickets by multiplying the number of adults
by the ticket cost. Then we will do the same
for children's tickets. Finally, we will add
the revenue from adult tickets to that of children tickets to
find the total revenue. All that's left now is to display to the user
the result we found. So we will add the
following command. Publish, the total
theater revenue is "," total revenue "," dollars. The last command we
will add is end_program, which states the
end of the program. We don't forget that
in order to work, we need to declare the variables we used at the beginning
of the program. Local_integers,
adults, kids, revenue adults, revenue
kids, total revenue. These are all the
commands we used, and now let's see an example to check if the program
we wrote works. For example, if the adults were 10 and the
children were 20, the program would display
the amount of $500.
8. Control Structures: Selection Structure (Conditional): If our problem
involves a choice, we need to use a
selection structure. For example, create
a program that decides whether we will
go on a trip or not, depending on the weather. We create a program
and ask the user to tell us what the
weather is like outside. If the answer is that
it is raining heavily, the program should tell us
that we will stay at home. Otherwise, we will go on a trip. In this case, we do not
follow specific steps, but there is the possibility of choice depending on
the weather outside. Generally, the selection
structure help us make a decision depending on whether the condition
is true or false. The general form of the
selection command is as follows. If true condition,
then do commands, otherwise, commands and
end_if. Let's see an example. We want to create a program that determines if an
integer is negative, or if it is greater
than or equal to zero. In this program, we ask the
user to input an integer. Then we first check if the
number is less than zero, or in a different case, if it is greater than
or equal to zero, and we display the corresponding
message to the user. Now, let's solve a slightly more complex problem
step by step. We want to write a program
that accepts 2 integers. If the 1st number is
greater than the 2nd, their sum will be displayed. Otherwise, their multiplication
will be displayed. First, we write the commands
in the declaration section, and we will complete them, at the end. Now, we need to ask the user of the program
to provide the integers. Then we will use the
command retrieve to input the numbers into
two variables, A and B. Next, we need to
check the condition, if the first number is
greater than the second. Thus, we use the selection
command, if_true. In the case that
the first number is greater than the second, we will give the command
to add the two numbers. We will place their sum into a new variable named C. If
this condition is not met, meaning any other condition, we will multiply the numbers, and the Selection structure
will be completed. In the end, we will display to the user the content
of the variable C, and the program
will be completed. We chose to place the
PUBLISH command after the END_IF to
display the result, but we could have
added it here and here. The only difference in this case is that we
write PUBLISH twice. We must not forget that
for our program to work, we need to declare the variables we used at the beginning of the program. LOCAL_INTEGERS: a , b , c Let's see if the program
we just wrote works. As we can see here, if the first number is
greater than the second, the program adds them. Whereas, if the
second is greater, the program multiplies them.
9. Control Structures: Multiple selection structure: Multiple choices are slightly more complex than the
Selection structure. as they apply to problems where different decisions can be made depending on the value
of an expression. Generally, we refer to multiple choices when we
have more than two cases. The general form of the multiple selection
command is as follows. If_true condition then_do
command or commands, else_if condition then_do
command or commands. Otherwise, command or commands,
end_if. Let's look at
an example that will help us understand the logic
of the multiple choice. We want to write a
program in which the user will give a
rating for a service from 0-10, and the program will display the appropriate
message to the user. If the rating is 0-3, it will display bad rating. If it is 4-6, it will
display moderate. And if it is 7-10, it will display very good. In this particular example,
we took 3 cases. If the rating is 0 -3,
display bad rating, else if it is 4-6, display moderate
rating, otherwise, display very good rating. The otherwise includes
all the other options, and even if someone enters a negative number,
it will go there. To be more correct, we should
say if true 0-3, ELSE_IF 4-6, ELSE_IF 7-10 In the case that we want to
account for someone entering a negative number and prevent the program
from getting stuck, we can say if_true
0-3, ELSE_IF 4-6 ELSE_IF 7-10, otherwise,
displays "invalid entry". Let's see how we will
write the program. Generally, as soon as this program runs, it
will do the following. With the PUBLISH command, it will display the message, "give the rating
of the service on a scale 0-10 to the user." It will wait until it
reads a number from the keyboard and will assign
it to the variable A. It will start performing the checks using
the IF_TRUE command until it finds the
first true condition and will execute the
commands within it. Then it will go to the commands below the END_IF if they exist. Otherwise, the program stops there or displaying the
appropriate message. At this point, it is
important to highlight the difference between
as_well_as and either. In our code, we added
as_well_as and not either, as both conditions need to be satisfied
at the same time. We would use either in a case where if at least one
condition is satisfied, the commands will be executed. For example, consider a program
that reads the grade of a written exam on a scale from 0-100
by two examiners. The final grade is given by the average score of
the two examiners. If the difference
in the grade is greater than or equal to 15, then it will display a message indicating that a 3rd examiner needs to review the exam, and the program will terminate. The program we should write is this: program_name Exam1
local_variables, LOCAL_REALS: a,b,final_grade START_OPERATION, PUBLISH,
"give the two grades" RETRIEVE a, b IF_TRUE (this) EITHER (this) THEN_DO PUBLISH "A third
examiner will also be needed" Otherwise, final_grade is
(a + b) / 2 PUBLISH "Final grade is",
final_grade
"end if, end program" Another example that shows
in detail the form of a program with multiple choice procedures
is the following. A telecommunications provider
applies price tiering for international calls, from 0-3
minutes $1 per minute, next 3 to 10 minutes
$0.80 per minute, and all remaining minutes
$0.50 per minute. We want to write a program
that will be given the minutes of a call and will
display the charge for it. We start our program with
the declaration section, where in this specific case, we have real variables
rather than integers as in previous examples,
because someone might input the minutes
of speech in decimal form. Next, we will ask the user to provide the
duration of the call. This will be done with the PUBLISH command to
display the message. Then the program will
read the number from the keyboard and assign it to the variable named duration. PUBLISH, "give the call duration in minutes", RETRIEVE duration. Next, we will handle
the case where the minutes are within the
limit of the first charge. So we will simply multiply the minutes by
the charge per minute. Then we continue
with the case where the duration is above
3 to 10 minutes. The result is the sum
of the charge for the first 3 minutes + the remaining minutes multiplied by the corresponding charge. That is, for the
first 3 minutes, we will multiply by $1, and for the duration minus
the first 3 minutes, we will multiply by $0.80. Next, if the duration of the
call is above 10 minutes, we do something similar. We calculate the charge
for the first 3 minutes, add the charts for
the next 7 minutes, and any remaining minutes
will be multiplied by $0.50. Then we will also consider the case where someone
enters a negative number. At the end, we will
show the output, which is the charge of the call, and we close the program with
the command end_program. We must not forget that
for our program to work, we need to declare the variables we used at the beginning
of the program. LOCAL_REALS: duration, charge Now, let's run the program. Suppose the call
duration is 11 minutes. The program enters
the 3rd case and gives the correct result.
10. Control Structures: Nested Procedures: Nested procedures refer to the possibility of having
a case within a case. Here is an example.
Create a program that reads the height and
hair color of the user. If the height is greater than 6.2 and the user is blonde-haired, it displays tall and blonde-haired. If the height is below 6.2
and the user is blonde, it displays average
height and blonde-haired. In this case, we have
two "if" statements. One "if" is nested within another. So we have to write a program that roughly
has 4 cases. if the user is tall
and blonde-haired, if the user is tall and dark-haired If the user is average
height and blonde-haired, and if the user is average
height and dark-haired, Let's see now how we
would write this program. We give a name
with program_name. We start variables
with local_variables. Start_operation. PUBLISH "Give the height in feets"
RETRIEVE height. PUBLISH "Give the hair colour:
blonde-haired or dark-haired" RETRIEVE hair
IF_TRUE height > 6.2 THEN_DO
IF_TRUE hair = "blonde-haired" THEN_DO PUBLISH "tall and blonde-haired" Otherwise, PUBLISH
"tall and dark-haired" We close the IF statement
with END_IF. Otherwise, IF_TRUE hair = "blonde-haired"
THEN_DO PUBLISH "average height and blonde-haired"
otherwise, PUBLISH "average
height and dark-haired" END_IF
END_IF, and END_PROGRAM. We add LOCAL_REALS: height
and LOCAL_CHARACTERS: hair The only difference here
is that we have an end_if that marks the
end of its nested if_true, and one for
the external one. It's important to note
that in this example, we are not considering
cases where someone inputs something different
from what we asked for. Let's look at an example
that we will solve together, write a program that reads the grades 0-10
of a student in physical education in 2 sports and displays
which he passed. We start our program with
the declaration section, where in this specific case, we have real variables because someone might input the
grades in decimal form. First, with the
PUBLISH command, we will ask the user
for the 2 grades. Then the program
will read and assign them to the variables
A and B respectively. PUBLISH "give the grade for the first sport on a scale 0-10" RETRIEVE A, PUBLISH "give the grade for the second sport on a
scale 0-10" RETRIEVE B. Then we need to check the
conditions for each case. The first condition we
are going to check is if the student passed the first
and also the second subject. In this case, a
congratulation message will be displayed to the user. Next, the ELSE_IF will be executed only if the second
subject is not passed. While we know from
the external IF_TRUE that the first
subject was passed. In this case, we
will display that the student passed only
the first subject. Otherwise, PUBLISH "Invalid entry for the second subject" END_IF, then we will close the nested IF_TRUE b greater than
or equal five, AS_WELL_AS b less than or equal 10 with the
end_if command. Next, we will move to the case where the student did not
pass the first subject, and neither the second one. We will display that the student did not pass any subject. With PUBLISH "you do not pass
the two subjects" If the student did not
pass the first subject, which we check in
the external "if", but passed the second
subject checked with else_if, we will display that the student passed only
the second subject. The program will execute the commands inside
the otherwise only if the given number is out of borders of 0-10. Then we close the nested "if" and the only thing
left is the case where an incorrect value is given for the first
subject in variable A. Then we close the
external if_true, and the program is completed with the command end_program. Let's see if the program we just wrote runs. We entered two numbers where
both are greater than five, and it displays the
appropriate message. But if you enter numbers
for the other cases, you will see that it also displays the
appropriate message.
11. Control Structures: Repetition Structure : When we need to perform
a step many times, we use a repetition structure. For example, if we want to display all the integers 1-100. To avoid writing a program that includes all these numbers
that is large and tedious, we use one of the three
repetition structures. The repetition structures
are as follows. When we know in advance how many times we want
the loop to execute, we use the loop structure
that is for loop I, starting at zero
and ending three, PUBLISH i end_loop. And includes all the necessary
elements for the loop, which is the initial
value of the variable I and its final value.
Let's see an example. We want to write a
program that will add all the integers 1-100
and display their sum. Program name addition100, local_variables, local_integers: i, sum.
Start_operation. We initialize the sum with 0. For loop I, starting
at zero and_ending 100, sum is sum + i
END_LOOP PUBLISH sum
END_PROGRAM In this example, the variable i increases by one
in its iteration, which is why we do not need
to write it in the program. Here we should note
that the default steps that increase i is one. If we want it to be anything
else for example 3, we should declare it with
the command with_step. Let's also look at
such an example. We want to find the sum of
the even integers 1-100. The program we will write is not much different
from the previous one. The only difference
is that here we have added the step as a third
argument, which is two. In this case, we write
the name of the loop, the variable i with
its range of values, that is 2-100, and
finally, the value 2, which is the step by which the variable i increases
in its iteration. The second repetition
structure is as follows. AS_LONG_AS condition
DO_THE_FOLLOWING Command or commands
END_LOOP Let's look at an
example in this case. We want to write a
program in which the user will input
positive numbers, and the program
will display them. The program will be terminated when the user inputs
a negative number, and does not display the
negative number itself. After start operation,
RETRIEVE x AS_LONG_AS x > 0
DO_THE_FOLLOWING PUBLISH x
RETRIEVE x END_LOOP
END_PROGRAM In this case, before
the loop starts, the variable x must either be defined or
read from the keyboard. Suppose in the above example, a negative number is given
directly as the first input. In this case, the program will
not enter the loop at all, and it will terminate there. However, if it was positive, it would go on to repeat all the steps under
the loop AS_LONG_AS. When the program receives
a negative number, it will not enter
the loop to display the negative number
because of the condition, but will go directly to the
commands after the "end loop". In this specific case, there are no other commands, so the program terminates there. The BEGIN_LOOP UP_UNTIL
statement indicates that the commands will be executed until the
condition is true. Once the condition is true, the program continues with the commands that
follow the UP_UNTIL. It is structured as follows. BEGIN_LOOP command or commands. UP_UNTIL condition. The program we saw in the
AS_LONG_AS structure, which reads and displays all
positive numbers can be written correspondingly using
the “BEGIN_LOOP ” structure. In this loop case, the
program does not need to know the value of x
variable before the loop. So we have RETRIEVE command
inside the loop and the condition will be checked at the end of the iteration,
not at the beginning. Let's assume that in
the above example, a negative number
is directly given. The loop starts with
the command begin_loop, reads the negative
number and displays it. Then the condition is
checked, and the loop ends. However, if the
number were positive, it will go on to repeat all the steps under the
begin_loop command. These two loops,
the AS_LONG_AS and BEGIN_LOOP have three
differences between them. For the “AS_LONG_AS”
loop to execute, the condition must be x
is greater than 0, whereas in the BEGIN_LOOP, x must be less than 0. As we can see, the
two conditions are opposite to each other. In the case where
the first number given by the user was negative, the AS_LONG_AS loop would
not execute at all, while the begin loop would execute once before terminating. Therefore, the AS_LONG_AS loop might not execute even once, as the check is done at
the start of the loop, while the “BEGIN_LOOP”
will execute at least once. However, for the condition to be checked in the
“AS_LONG_AS"command, the variable x must be
defined before the loop. Whereas in the “BEGIN_LOOP” the variable is usually
defined within the loop. So far, we have discussed all the commands we need
to write a program. Next, we will use these
commands to solve more complex problems
using arrays. Please let me know if you have any questions in the discussion.
12. Arrays: Introduction: So far, we have studied the basic control structures
written in pseudocode. However, there are
certain categories of problems that require
different types of structures to solve. What are these structures? In both programming
and pseudocode, when we need to manage a large volume of data
of the same type, we can use arrays
instead of variables. In this section, we will see
what we define as an array, When we use arrays, what types of arrays there are and how arrays work in pseudocode. This is the definition
for arrays. But what does this mean? Suppose we have the following
array that contains the maximum humidity of its
day for the previous month. This array can be
defined as follows. Array, and in brackets [i]. The values of range 0-30 for the 31 days
of the previous month. The i is the index of the array. For example, if we want to use the humidity of the day
4 in our program, we refer to the array with humidity[3], which equals 88. In this case, the
index is an integer either constant or variable and enclosed within
the brackets. In arrays, we have data
of the same type, which can be numeric,
logical, or characters. For each array we create, we must declare its name, type, and the number of
elements it will contain. The type of an array
can be one dimensional, two dimensional, etc, and declared in the beginning of the program, as we will see. We will look at one dimensional and two dimensional arrays, since our goal is to
introduce coding.
13. Arrays: One dimensional: Let's start with one dimensional arrays and see an example. Suppose we want to create a program based on the
array we saw previously, which contains the maximum
humidity of a month. We will write a program
that reads the humidity of 31 days and calculates the average maximum
humidity of the month. Without using an array, such a program would
be written as follows. In this case, we used only
variables without an array. But if we want to find out how many days the humidity
was less than the average without
asking the user for the humidity values
for 31 days again, we would need to "store" all the humidity values and compare them
with the average. We would need to create
31 different variables corresponding to the
humidity of 31 days. Therefore, the program we would write would have 31
RETRIEVE commands. and 31, if_true commands. Such a solution
might be correct, but it is not practical for
a large amount of data. For example, if we want the humidity values
of an entire year. In this case, the solution
is given by using an array. In this array, the
humidity values will have continual positions, and each element
of the array will be identified by its index. For example, humidity[30]
corresponds to day 30 and contains the
humidity value of 50. Since we used only one index
to refer to an element, our array is one dimensional. The program, we will write
to find out how many days the humidity is lower than the average value of the
month is as follows. Initially, we create
an array called humidity and allocate
31 positions, which is always the
size of the array. It's important to note here that the size of
the array is fixed, and it cannot have
more elements than the size declared
during its creation, nor can it have fewer. In this particular case, it cannot be different
from 31 elements. Then we assign the value
0 to the variable "total" and we will see later
why we do this. Next, we need to
fill the array with the humidity values provided
by the user for each day. A position in the array
represents a day of the month, and each element in the array is a value
representing humidity. So since we know exactly how many iterations we will
need to fill the array, we always use the “FOR_LOOP”
iteration with i taking values for each day from the first to the 31st day. Then we display the message that the user will see
on their screen, so they understand what
they need to input, which is "give the humidity for the day" followed
by the variable i, which is the number of
the respective day. We place the humidity
value that the user just provided into the corresponding
position in the array, using the humidity
array and the index i. Since we need to calculate the average humidity
for all days, we will now use the
variable "total", which we initialized to
0 at the beginning. By the end of the loop, this variable will contain the sum of all the humidity
values for the month. Next, we will divide total
by 31 to find the average. Now, to find out
how many days had lower humidity than the
average of the month, we will need to search through
the data in the Array. To do this, we will use a loop from 1-31 to access the values
contained in the Array. In each iteration, we convert
the humidity value of the current day from the first to the last with
the monthly average. If a day with lower humidity
than average is found, we have a counter, which is essentially a
variable named "days". This counter increases by one Ieach time the previous
comparison condition is met. After checking all the
elements in the array, we will display two
messages to the user. One will be the message. "The average humidity
of the month is" followed by the
value of the average, and the other will
be the message "The days with lower
humidity than the average are:" followed
by the number of days. At this point, the program concludes with the
command end_program. That was our example for
one dimensional arrays. Now let's look at an example with a two dimensional array.
14. Arrays: Two dimensional: In the case of two
dimensional arrays, we use two indices to
specify an element. For example, if we wanted to calculate the average
humidity for 10 cities over a month and determine
how many days the humidity was higher than the corresponding average value. The array we would create
would be as follows. This array is a 31 by 10, a two dimensional array, so we have 31 humidity values, but for 10 different cities, meaning a total of
310 humidity values. To define the elements of
a two dimensional array, we use two indices
in the form Array[r,c] The first corresponds to
the rows of the array, and the second to the columns. r is for rows at the time of defining the array and
row index during access. c is for columns at
the time of defining the array and column
index during access. For example, in the
previous array, the element humidity[30,1]
has a value of 50. What value would the
element humidity[2,10] have? The correct answer is 73. To solve the previous problem, we would write the
following program. The logic is the same as
in the previous example, where we had a one
dimensional array. But here, the difference is that in addition
to the variable i, we also have the variable j. Let's see how we would create the array for just 1
day for all 10 cities. FOR_LOOP j, starting at
1 AND_ENDING 10 PUBLISH "Give the humidity for the city", j RETRIEVE humidity[j]
END_LOOP Now it becomes easier
to see how we would do this with a two dimensional
array for 31 days. FOR_LOOP i STARTING_AT 1
AND_ENDING 31 FOR_LOOP j STARTING_AT 1
AND_ENDING 10 PUBLISH "Give the humidity
for the city" , j, "the day", i. RETRIEVE humidity[i,j]
end_loop, and end_loop. Essentially, we
added one more loop for the 31 days of the month, which will contain
the previous loop that handled the humidity
values of each city. Additionally, the i we added in the PUBLISH and RETRIEVE commands refers to the indices of the
two dimensional Array. Let's see how this array
would be filled in practice. Initially, we enter the
loop with i equals one. That is for the first day, and directly in the
loop j =1 , the humidity for the
first city will be added. Then j will become 2 while we are still at i
equals 1 and so on. So when j equals 10, we will have the humidity values for the 10 cities
for the first day. The j loop will then end. i will become 2, and J will again take values 1-10 until the values for the
second day are completed. This will continue
until i equals 31, and j equals 10, at which point the outer
loop i will also end. At this point, the array will be
filled with the data we want. Now, let's see how to find the average humidity
for each city by referring to the array and utilizing the data
it already contains. Since we want to read
the array by city, this means that we need to read the data vertical by city. To achieve this, this time
the outer loop will be j, and the inner loop will be i, FOR_LOOP j STARTING_AT 1
AND_ENDING 10 FOR_LOOP i STARTING_AT 1
AND_ENDING 31 Initially, we want a
variable called "total" that will hold the sum of
all the values for 1 city. Based on this sum, we will find the average
for each city. And before moving on
to the next city, we must reset this variable. FOR_LOOP j STARTING_AT 1
AND_ENDING 10 We initialize total with 0. FOR_LOOP i STARTING_AT 1
AND_ENDING 31 Total is what was total
previously plus humidity[i,j] We close the loop, and the average is the
total divided by 31. To store the average
for each city, we will create a one
dimensional array with the average of each
city called "average[j]". At this point, we have
filled the average array, which contains the
average for each city. We now want to search
through the array to see how many days the humidity was greater than the city's average. We will examine the
array vertically, comparing the humidity of its day with the city's average. For the days where the humidity is higher than the average, our counter days will increase. Before the loop for
the first city ends, we display the city's average
humidity and the days when the humidity was higher than the average to the user. Then this loop will be repeated
for the remaining cities, where each time our
counter days will reset. After this, the program
will be complete. As we saw, the only
difference between one dimensional two
dimensional arrays is the number of indices used, meaning array[i] for one dimensional and array[i,j] for two
dimensional arrays. To fill a one-dimensional array
, we use a loop. While for two
dimensional arrays, we need a nested loop. Until now, we have seen
how to declare an array, how to fill the array with data, and how to search an array in
order to make calculations. Now, we are going to look at something more challenging
than what we've seen so far, which is sorting an array.
15. Arrays: Sorting: Sorting an array is a very
important operation that arranges the data of an array in ascending or
descending order. At the same time, it's
an opportunity to look at a more demanding example
than those we've seen so far. Let's now see an example of how to sort an array
in ascending order. We have this array.
Nine, five, seven, and two, and we
want to sort it in ascending order so that
it becomes like this. Let's see how we would think
about building this program. Initially, we know that the
array elements are 4. We will need a loop to move the number two to the
beginning of the array. For this to happen,
we will compare the last element of the array
with all the previous ones. And we will know at the
end of the loop that the first element of the array is also the smallest
in the array. So starting from the
last number array[4], we will compare the number
2 with the one before it, array[4-1], and if it's smaller, we will move it up
one row in the array. This will be repeated
for the element array[3] with array[3-1] That is 2 with 5. So it will become like this. And finally, it will be
repeated for the element array[2] with array[2-1] that is 2 with 9. So it will become like this. There's no need to continue the loop comparing array[1] with array[1-1] as there is no array[0]
in this array. This is because we started
counting the array from 1 to 4. We could start counting
the array from 0 to 3 with no problem as it means
the same as 1 to 4. If we had started our array
with indices 0-3, there would be no
element -1 in our array, and the last loop could
not convert the element array[0] with array[0-1]. Because simply put,
array[-1] does not exist. The number of repetitions
needed to move the number 2 to the
first row was 3. For this reason, we will start our loop with i=4 to 2. step of -1 so that we start from the end of the array
and gradually move upwards. At this point, we want
to swap the content of array[i] with array[i-1] To achieve this, we will use a variable named "temp" as
a temporary variable. In this variable, we will
store the current value of array[i], which in the first
iteration equals 2. So we have i equals 2
and 10 equals 2. Next, we will assign to array[i] the
value of array[i-1] meaning the 2 in array[i]will
be replaced with 7, and we will put the
old value of array[i], (which we stored in the temp variable and equals 2 ) into array[i-1]. If we didn't use
the temp variable, we would lose the previous
value stored in array[i] during (this). So the program we would write
up to this point is this. At this point, the sorting of the array is not yet complete as only the smallest element has been sorted to the
beginning of the array. This process must also be done for the remaining elements. Therefore, we will use one more outer loop
to achieve this. This loop with variable j will take values from element
2 to element 4. Because only 3 comparsons are enough to compare all the
numbers with each other. This makes sense because
when we compare N numbers, the number of comparsons we
will make is N-1. Let's see how this works, and we will explain
it step by step. We have already sorted
the number 2 and start the same process from the
last element of the array. We compare array[4]
with array[4-1] that is 7 with 5. And since 7,
greater than 5, these two elements will
not change places. So the array at this
step will remain as is. Next, we will compare
array[3] with array[3-1] that is 5 with 9, and since 5 less than 9, the array will become as follows. The second outer
loop stops here as there is no need to
compare 2 with 5. Another loop follows to
sort the last element. We compare array[4] with array[4-1] and since 7, less than 9, a swap of
the two elements will occur, and the array will
take its final form. The final program
will be like this. It's worth noting that in this
final form of the program, in the loop i we replaced
the 2 with the variable j. Let's now see why step by step. We use the variable j to count the number of
comparisons we need. However, as the comparisons
we make increase, so do the elements
that get sorted. For this reason,
in the inner loop, we start the comparison from the last element like array[4]. But the number of comparisons we will need will not be constant. It will decrease each
time the outer loop runs. Meaning j will increase, and that means that the
number of inner loops we need, will decrease after
every external loop. This is the process we follow to sort the array using
the bubble sort method. It's worth noting
here that this is one of the simplest sorting
algorithms to understand, but at the same time, it's one of the most time consuming.
16. Project: At this point, we have
completed both our theory and the example exercises we
demonstrated and solved together. You can now solve problems
on your own using programs. To start, you can begin
with our project. All the information
you need to solve this problem is found in
the previous lessons. A sample solution has already been uploaded to the
class project gallery. However, it's not
the only solution. That's the beauty
of programming. It can be done in
many different ways as long as it produces
the correct results. I would be happy to
see your program with the solution to the problem
written in Pseudocode.
17. Conclusion: As we conclude our lessons, let's take a moment to
review what we have covered. Initially, we went back in time and looked at the
evolution of how we give commands to computers from machine language to 4th
generation languages. Next, we discussed the
concept of a problem, and specifically
the thought process we follow to solve a problem. With these basic
concepts in mind, we were then ready to
talk about Pseudocode. We explored how programs
help us solve problems, the Control structures we use, and how each one functions. We then moved on to slightly more complex aspects of programming and
talked about arrays. When we use them to help us, how we search for an
element in an array, and how we sort them. Now, the only thing
left is to practice what we've already learned
by solving more exercises. And we are ready to move into
the field of programming. I'm Giannis Demertzidis. Thank you all for joining me on this journey through coding. Feel free to ask anything
you didn't understand, or if there's any part of the course you think
could be improved. Don't forget to follow
me for more content. And remember, stay curious, stay inspired, and
never stop learning.