Theorem of Structured Programming: What Is An Algorithm?
Theorem of Structured Programming: What Is An Algorithm?
All computational problems could be solved using one or 3 structures of the following
programming structures:
• Sequence
• Selection (Decision or Fork)
• Iteration (Loop or Repetition)
All logic problems in programming can be solved by forming algorithms using only the three
logic structures, and they can be combined in an infinite number of ways. The most complex
the computing need, the more complex the combination of structures.
What is an algorithm?
Computational problem
All problems that have a solution that can be found following a groups of steps well defined in
some order (is possible to establish a sequence of steps) is a computational problem.
Wikipedia
All problem that have no a unique solution or is impossible to ask or is not possible to find an
algorithm.
2. How we can do to improve the sales in March 2020 considering we are in April 2019?
5. What is the infallible method to make gorgeous girl fall in love with you?
Some interesting problems are computational and we need to know some steps in order to
solve these using a computer I mean using computational programs, first we need to know how
to find a good strategy for solving.
Before make some computational program to solve a computational problem, we need to know
what to find the best Algorithm to this problem.
Sequence
Is one of the three basic logic structures in computer programming. The other two logic
structures are selection and loop.
A sequence structure consists in a group of steps ordered and executed in a sequential manner.
A step could be an action, or event, once it finished the next step takes place. None of the steps
can be avoided or skipped; all have to be executed in strictly order.
Many things have to follow a sequence in order to be well doing, for example a cooking recipe,
in which you can find three main steps that must be secured in strict sequential order.
1. Collect the ingredients: They must be detailed and the quantities to be used.
2. Prepare the dish: The preparation steps should be indicated in an orderly and accurate
way if we want everything to go well.
3. Present the dish: Consists to indicate the steps to serve the food on the plate and
decorate or complement it with some accompaniment or some sauce.
Examples:
Problem 1. Suppose you want to calculate how long a car will arrive at a gas station that is 100
miles away, if the speed is 20 miles per hour.
1. Get the distance: The distance is 100 miles, then create a variable to storage this value.
d = 100
2. Get the speed: The speed is 20 miles / hour, then create a variable to storage this value.
s = 20
3. Calculate the time as value of distance divided by value of speed, then create a value for
storage the calculated vale.
t = d / s = 100 / 20 = 5
Speed.java
Line Sentence
1 import java.util.Scanner;
2 public class Speed {
3
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 // 1. Getting Data
7 System.out.println("Enter the distance in miles:");
8 int d = sc.nextInt();
9
10 System.out.println("Enter the speed in miles / hour:");
11 int s = sc.nextInt();
12 // 2. Processing
13 int t = d / s;
14 System.out.println("The time it takes is " + t + " hours."); // 3. Presenting results
15 }
16
17 }
In Java there are several ways to get input from the user, who has to type in the console. One
Java class that is useful for this is Scanner class.
Scanner class comes under java.util package that comes with Java Standard Edition an the
others editions, hence the first line of the program is import java.util.Scanner; which allows the
user to read values of various types in Java.
The import statement line should have to be in the first line the java program, and we proceed
further for code.
In line 1 The class Scanner is imported to the program in order to use their method nextInt( )
which enable capture integers from console, the user has to type some integer value, then a
value is assigned to some variable, in example in lines 8 and 11 2 integers has to be entered by
user and this will be captures by the method nextInt() of the Scanner class and assigned to the
variables d and s respectively.
In line 13 the calculation is performed, and finally in line 14 the results are presented.
Execution
import java.util.Scanner;
3. Notice is changed the name of Speed class for Main. You will paste the code replacing the
content for Main.java program, as you see in the picture below. Then make click in Run.
4. Please verify that import java.util.Scanner; is the first line in program Main class.
As you can see the program asks for the value of distance, then for the value of the speed of
car and finally calculates the time in hours and present the results in console.
If still you have problems to get the code, try this link: https://onlinegdb.com/HJyRcllKE
Problem 2. At the Central Bank there are some ATMs (automatic teller machines) that want to
allow customers to make withdrawals of money. Let us suppose that a customer type an
amount that he wants to retire, by example 380 dollars, then the Bank wants you to do a
program to obtain:
1 bills of 50 dollars
1 bills of 20 dollars
1 bills of 10 dollars
They have huge amounts of the next bills only: 500, 100, 50, 20 and 10 dollars. They have to
send the fewer number of bills to the customer.
For the example, as you can see there are 4 bills and the Bank need the fewer number of bills to
send.
1. In the search of a generic logic we could say let’s divide the amount by each value of the
Bills beginning by to mayor value and descending to the minor value. This value (the
integer part) is the number of bills to send. Each time we will recalculate the amount as
the modulus with the current value of bill.
The bills are: 500, 100, 50, 20 and 10 dollars, let’s begin with 500.
380 / 500 = 0, then 0 bills of 500 dollars; get the modulus (I mean the remainder after division
of one number by another).
Getting the modulus: 380 % 500 = 380, this will be the new amount, let’s continue ☺
380 / 100 = 3, then 3 bills of 100 dollars will be send to customer till now
Getting the modulus: 380 % 100 = 80, this will be the new amount, let’s continue ;)
Third task: Using 50 dollars bill
Getting the modulus: 80 % 50 = 30, this will be the new amount, let’s continue ;)
Getting the modulus: 30 % 20 = 10, this will be the new amount, let’s continue ;)
Results to show
1 bills of 50 dollars
1 bills of 20 dollars
1 bills of 10 dollars
In order to do this task more powerful and avoid the disgusting 0 bills of 500 dollars, we will see
later Selection and Loop structures.
Data to request
ATMCashier.java
Line Sentence
1 import java.util.Scanner;
2 public class ATMCashier{
3
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.println("Enter the amount:");
7 int amount = sc.nextInt();
8 int number = 0, currentBill = 0;
9 // We will use Division operator / when
10 // integers are involved return an integer
11
12 // First task
13 currentBill = 500;
14 number = amount / currentBill;
15 amount = amount % currentBill; // Modulus operator
16 System.out.println("" + number + " bills of " + currentBill);
17 // Second task
18 currentBill = 100;
19 number = amount / currentBill;
20 amount = amount % currentBill; // Modulus operator
21 System.out.println("" + number + " bills of " + currentBill);
22 // Third task
23 currentBill = 50;
24 number = amount / currentBill;
25 amount = amount % currentBill; // Modulus operator
26 System.out.println("" + number + " bills of " + currentBill);
27 // Fourth task
28 currentBill = 20;
29 number = amount / currentBill;
30 amount = amount % currentBill; // Modulus operator
31 System.out.println("" + number + " bills of " + currentBill);
32 // Fifth task
33 currentBill = 10;
34 number = amount / currentBill;
35 amount = amount % currentBill; // Modulus operator
36 System.out.println("" + number + " bills of " + currentBill);
37 }
38
39 }
Execution
Enter the amount, for example 380, you will have the expected result. It is not perfect in order
to improve this we will see now the Loop structure.
Selection structure sample
Is a structure created in order to execute evaluate if some piece of code (certain lines of your
program) will be executed or not by a logical condition that has to obey.
1. We will use the same logic: In the search of a generic logic we could say let’s divide
the amount by each value of the Bills beginning by to mayor value and descending to
the minor value. This value (the integer part) is the number of bills to send. Each time
we will recalculate the amount as the modulus with the current value of bill.
380 / 500 = 0, then 0 bills of 500 dollars; get the modulus (I mean the remainder after division
of one number by another).
Getting the modulus: 380 % 500 = 380, this will be the new amount, let’s continue ☺
And …
Improvements
Changes in code
Instead of do this:
Change for:
As you can see code is simple and easy to understand, because the changes take place in the
code inside the for statement.
The Selection structure
1 blocks in Java
The code executes sequentially by default
var1 = var2 ++ + 4;
{
int i = 0;
Boolean term = true;
System.out.println("i =" + i);
i ++;
}
2 IF and ELSE
This statement provides a selection of processes Basic. A Boolean expression controls statement to run.
If the expression is true, will take place the first expression is false will be the second.
SYNTAX
if (< condition logic >) < statement >; //The clause else is optional.
Third structure: To evaluate if one block of code will be executed or another block of code.
if (i % 2 == 0)
System.out.println ("pair is");
else
System.out.println ("is odd");
//
if (daysOfRent > daysRentalContracted)
System.out.println("First pay arrears for rent");
else
System.out.println ("Can rent new movies");
//
if (number > 0) {
System.out.println("The number is positive");
}
//
if (month < = 7) System.out.println("The tax is 18%");
else System.out.println("The tax is 19%");
3 IF nested
First example:
Third example:
4 common errors.
int x = 3, y = 5;
if (x > = 0 and < x) // and is a mistake use && instead
System.out.println("y is less than x");
else
System.out.println("x is negative");
//
int x = 7;
if (x = 0) // Wrong, if (x == 0) is the correct use
System.out.println("x is zero");
//
int x = 15, y = 24;
if (x % 2 == 0 & & and % 2 == 0); // y is missing here
System.out.println("x & y are even numbers");
It is an expression that returns a value. If the logical expression is true the first value is obtained. If the
logical expression is false the second value is obtained.
First example:
Tell Peter what he has to do depending on the day of the week he is today. The day is 1 to 5 for Monday
to Friday, 1 for Monday, 2 for Tuesday, etc. 6 and 7 is for Saturday and Sunday respectively. Another last
thing to consider: is the day is not form 1 to 7, say something about.
7 EXERCISES
Exercise 3
Results:
If he works more than 40 hours is paid $16 for each of the first 40 hours and
$20 per hour extra.
hoursWorked = 47;
Exercise 5
A year is leap if it is divisible by 4, except for some of them that are
divisible by 100 but not by 400. According to the year, determine the number
of days in a month.
switch (month){
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
days = 31; break;
case 2:
days = 28 + isLeap(year); break;
case 4: case 6: case 9: case 11:
days = 30; break;
}
1 WHILE
The while is the most simple of a loop. It has the following form:
int i = 1; // initialization
while (i <= 10) {/ / repetition condition}
System.out.println(i * 2); //body
i++; // iteration
}
The body will take place while the repetition condition is true
2 DO... WHILE
int i = 1; // initialization
do {
System.out.println(i * 2); // body
i++; // iteration
} while (i <= 10) // condition
3. Cycle FOR
In the case of the exchange rate, the source code will be:
for (;;) {
System.out.println("Hello world!");
}
4 COMMON ERRORS.
Case 1
While (height > 0); //; here is the mistake it generates an infinite loop
System.out.println (height--);
System.out.println("We landed");
Case 2
height--;
Case 3
System.out.println (height);
System.out.println("We landed");
5. the sentence BREAK
All loop, the BREAK statement transfers control outside the loop. They are needed when it comes to
infinite loops.
EXAMPLE
An employee has reached the age of retirement (65) and has worked since age 25. Your Compensation
is deposited in a Bank granted interest on these deposits. A new Government has decreed that this
settlement will have a maximum of 250000 dollars
Abandons the execution of the body and continues to the next iteration.
Exercise 1
Show the conversion of 1 to 10 USD in dollars, dollar-to-dollar assuming that exchange rate is 3.30
dollars / dollar.
Exercise 2
A person wants to invest $1000.00 on a bench, which gives you a 2% monthly interest. What will be the
amount of money that this person will within a year if reinvests it all the money?
}
Exercise 3
Simulate the behavior of a digital clock, printing the hour, minutes and seconds of a day from 00: 00:00
hours until 23:59:59 hours
Exercise 4
A person wants to invest $1000.00 on a bench, which gives you a 2% monthly interest. In few months will
have more than $1500, if reinvested each month all their money?.
for (;) {
money = money * 1.02;
if (money >= 1500) break;
month ++;
}
System.out.println (month);
System.out.println (money);
}
}