0% found this document useful (0 votes)
43 views

Theorem of Structured Programming: What Is An Algorithm?

The document discusses computational problems and algorithms. It begins by outlining the three structures of programming: sequence, selection, and iteration. All computational problems can be solved using one or a combination of these structures. An algorithm is then defined as a procedure or formula for solving a problem in a defined sequential order. Examples are provided of computational and non-computational problems. The rest of the document gives examples of using the sequence structure to solve computational problems, including calculating the time for a car to travel a distance given the speed, and determining the minimum number of bills needed to make a cash withdrawal. Pseudocode and a Java program are provided as examples.

Uploaded by

Hugo Onque
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Theorem of Structured Programming: What Is An Algorithm?

The document discusses computational problems and algorithms. It begins by outlining the three structures of programming: sequence, selection, and iteration. All computational problems can be solved using one or a combination of these structures. An algorithm is then defined as a procedure or formula for solving a problem in a defined sequential order. Examples are provided of computational and non-computational problems. The rest of the document gives examples of using the sequence structure to solve computational problems, including calculating the time for a car to travel a distance given the speed, and determining the minimum number of bills needed to make a cash withdrawal. Pseudocode and a Java program are provided as examples.

Uploaded by

Hugo Onque
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Theorem of Structured Programming

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?

It is a procedure or formula to solve a problem, based on the realization of activities in a


sequential way that really solves the problem with total certainty.

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.

In theoretical computer science, a computational problem is an object that represents a collection of


questions that computers might be able to solve. In example, the problem of factoring. "Given a
positive integer n, find a nontrivial prime factor of n." is a computational problem.

Wikipedia

Examples of Computational Problems:

1. How old are you?

2. How much we sold in March 2019?

3. How much are the benefits we got in February 2019?

4. How much is the sum of 1 to 10?

5. What is the factorial of 10?


Non computational problem

All problem that have no a unique solution or is impossible to ask or is not possible to find an
algorithm.

Examples of Non Computational Problems:

1. How many years will you live?

2. How we can do to improve the sales in March 2020 considering we are in April 2019?

3. How we can improve the benefits in the future?

4. How many stars are the whole Universe?

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


2. Prepare the dish
3. Present the dish
Cooking Recipe

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.

A computational program is similar to a Cooking Recipe, a program has:

1. Data to be used (equivalent to the ingredients).


2. Procedure of calculations and operations (which is equivalent to the preparation of the
plate, if something is not indicated in the correct order, everything can go wrong or very
badly).
3. Presentation of the results (which is equivalent to the presentation of the dish),
indicating how the results will be presented in a clear and consistent manner to avoid
errors or misinterpretations.

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.

Algorithm for problem 1

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

4. Show the answer

The time it takes is 5 hours


Java program

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

In order to run this program, follow the next steps:


1. Go to the next link: https://www.onlinegdb.com/online_java_compiler
2. Paste the code contained in Speed.txt located in Section 1, Class 2 Flow Control: Sequence,
Selection & Loop. And then made click to Run. If you cannot find the file paste the next code:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter the distance in miles:");
int d = sc.nextInt();
System.out.println("Enter the speed in miles / hour:");
int s = sc.nextInt();
int t = d / s;

System.out.println("The time it takes is " + t + " hours.");


}
}

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:

3 bills of 100 dollars

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.

Algorithm for problem 2

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.

Try the algorithm

The bills are: 500, 100, 50, 20 and 10 dollars, let’s begin with 500.

First task: Using 500 dollars 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 ☺

Second task: Using 100 dollars bill

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

80 / 50 = 1, then 1 bill of 50 dollars more will be send to customer till now

Getting the modulus: 80 % 50 = 30, this will be the new amount, let’s continue ;)

Fourth task: Using 20 dollars bill

30 / 20 = 1, then 1 bill of 20 dollars more will be send to customer till now

Getting the modulus: 30 % 20 = 10, this will be the new amount, let’s continue ;)

Fifth task: Using 10 dollars bill

10 / 10 = 1, finally 1 bill of 10 dollars more will be send to customer

Getting the modulus: 10 % 10 = 0, this will be the new amount, no more to do

Results to show

0 bills of 500 dollars

3 bills of 100 dollars

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

Enter the amount: 380


Java program

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

In order to run this program, follow the next steps:

1. Go to the next link: https://www.onlinegdb.com/online_java_compiler


2. Paste the code contained in ATMCashier.txt located in Section 1 Class2 Flow Control:
Sequence, Selection & Loop. And then made click to Run. If you cannot find the file paste the
next code:
3. Notice is changed the name of ATMCashier 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.

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.

Example with the ATM Cashier:

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.

First task: Using 500 dollars 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

1. If 0 bills we have to send, just don’t be considered in the results


2. If 1 bill have to be send, in the results we print just 1 bill and not 1 bills as is
printed now with the former logic.

Changes in code

Instead of do this:

System.out.println("" + number + " bills of " + currentBill);

Change for:

if (number == 0) System.out.print(""); // print nothing


else {
if (number == 1) System.out.print("1 bill of " + currentBill);
else System.out.print("" + number + " bills of " + currentBill);
}
You will have:

As you can see 0 bills of … is no longer appears.


Loop structure sample
Is a structure created in order to execute the same piece of code (certain lines of your program)
repeatedly in a controlled way by a logical condition or a in a counted way.

Example with the ATM Cashier:

The improvements go in order to write less code. Try this link:


https://onlinegdb.com/r1OCt4WYE

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

A set of sentences require keys {} to group together as a block.

Between braces {} block is also known as a compound sentence.

A simple sentence is an expression that ends with a semicolon.

var1 = var2 ++ + 4;

Each block is executed as a single sentence within the stream.

{
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

First structure: To evaluate if some statement (instruction) will be executed or not.

if (< condition logic >) < statement >; //The clause else is optional.

Second structure: To evaluate if one statement will be executed or another.

if (< condition logic >) < statement >;


else < statement >;

Third structure: To evaluate if one block of code will be executed or another block of code.

if (<Condition logic ) >) {


_________;
_________;
}
else {}
_________;
_________;
}
Examples:

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

When many conditions are required, IF statements can be nested.

You should be careful in the correct use of the ELSE statement

First example:

if (speed > = 30)


if (speed > 100)
System.out.println("We're going too fast");
else
System.out.println("We'll arrive on time");
else
System.out.println ("that slow go");

Second example: Other way to do the same

if (speed > = 100)


System.out.println("You're going too fast");
else if (speed > 30)
System.out.println ("You're driving well.");
else
System.out.println("You're going too slow");
It is a good habit to nest sentences that are contained within others in order to have a good clarity in the
code and in order to make it easier to maintain it (this is called maintainability of code).

This approach is used, because that creates a complicated code to understand.

It is preferable to use the keys {} to separate blocks.

Third example:

if (speed >= 25) {


if (speed > 100) {
System.out.println("We're going too fast");
} // End of if (speed > 100)
else {
System.out.println("We'll arrive on time");
} // End of if (speed > 100) - else
} // End of if (speed >= 25)
else {
System.out.println ("Being slow mobility");
} // End of if (speed >= 25) - else

4 common errors.

Find errors in the following examples.

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");

5. The conditional operator (?:)

It is an alternative to the structure if... else

if (month < = 7) tax = 0.18;


else tax = 0.19;
Conditional operator: (<condition>) ? <Expresion1> : <Expresion2>

tax = (month < = 7)? 0.18: 0.19;

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.

6. The SWITCH statement

It is used when it is required to take an action among a number based on an expression.

• The expression must be byte, char, short, or int.


• Also since JDK 1.7 could be a long, double, float, String, or any other type.
• If the expression matches a condition, it runs.
• If it does not equate to any conditions, is marked with default judgment.
• The conditions must be constant.
• Use break to exit switch
• Always set a default option.

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.

int day = 4; // To be changed


switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("You have to go to work ");
break;
case 6:
case 7:
System.out.println ("Stay at home and have a good rest");
break;
default:
System.out.println("In what planet do you live?");
}
Second example: Evaluate if some character is a vowel or a consonant.

char letter = 'e';


switch (letter);
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'w':
case 'W':
case 'u':
case 'U':
System.out.println("Is a vowel");
break;
default: System.out.println("Is a consonant");
}

7 EXERCISES

Exercise 1 What is age?

public class Age {}


public static void main (String [] arg)
{
int age = 15;
if (age < = 18)
System.out.println ("You're in the childhood");
System.out.println ("The age is a State of mind");
}
}

Exercise 2 The best score, first: try to solve this

public class Score {


public static void main (String [] arg)
{
int yourScore = 85;
int myScore = 60;
int bestScore...

System.out.println ("Best score is:" + bestScore);


}
}
Solution using conditional operator

public class Main


{
public static void main (String [] arg)
{
int yourScore = 85;
int myScore = 60;
int bestScore = (yourScore > myScore) ? yourScore : myScore;

System.out.println ("Best score is: " + bestScore);


}
}

Exercise 3

In a Supermarket X there is a 20% discount to customers whose purchase


exceeds 300 dollars.What will be the amount that a person pay for your
purchase?

public class Buy {

public static void main(String[] args) {


double purchase, discount, total;
purchase = 410;
discount = purchase * 0.20;
total = purchase - discount;
if (purchase > 300) {

System.out.println("The discount is: " + discount);


System.out.println("The total payable is: " + total);
} else {
System.out.println(
"Without discount, the total is: " + total);
}
}
}

Results:

The discount is: 82.0

The total payable is: 328.0


Exercise 4

A worker needs to calculate their weekly salary, which is obtained in the


following way:

If he works 40 hours or less it pays you $16 per hour

If he works more than 40 hours is paid $16 for each of the first 40 hours and
$20 per hour extra.

public class Main


{
public static void main (String[]args)
{
int hoursWorked, extraHours, weeklySalary;

hoursWorked = 47;

if (hoursWorked > 40)


{
extraHours = hoursWorked - 40;
weeklySalary = extraHours * 20 + 40 * 16;

System.out.println ("The salary with overtime is of " + weeklySalary);


}
else
{
weeklySalary = hoursWorked * 16;
System.out.println ("Your salary is " + weeklySalary);
}
}
}

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.

public class Month {

public static void main(String[] arg) {


int year = 2004;
int month = 02;
int days = 0;

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;
}

System.out.println("The month has " + days + " days");


}

private static int isLeap(int year) {


int leap = 0;
if (year % 4 == 0){
leap = 1;
if (year % 100 == 0) leap = 0;
if (year % 400 == 0) leap = 1;
}
return leap;
}
}
The Loop Structure

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

Performs the condition of repetition at the end of the block.

It has the following form:

int i = 1; // initialization
do {
System.out.println(i * 2); // body
i++; // iteration
} while (i <= 10) // condition

3. Cycle FOR

The definition of a repetitive cycle combines in a sentence.

In the case of the exchange rate, the source code will be:

for (int i = 1; i < = 10; i ++) { }


System.out.println(i * 2);
}

Initialization and iteration can be composed.

for (int i = 0, j = 10; i < j; i ++, j-) { }


System.out.println (j-I);
}
You can create infinite loops.

for (;;) {
System.out.println("Hello world!");
}

4 COMMON ERRORS.

The space shuttle is located at an altitude of 10 Km and is in phase of landing.

Case 1

int height = 10;

While (height > 0); //; here is the mistake it generates an infinite loop

System.out.println (height--);

System.out.println("We landed");

Case 2

int height = 10;

While (height > 0)

System.out.println (height); // infinite loop height never decrease

height--;

System.out.println("We landed ");

Case 3

int height = 10;

for (; height > 0; height-); //; here generates an infinite loop

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

public class Main


{
public static void main (String[]args)
{
int salary = 2500, age = 30;
double interest = 10.00 / 100.00, liquidation = 0.00;
while (age <= 65) {
liquidation = (liquidation + salary) * (1 + interest);
if (liquidation >= 250000) {
liquidation = 250000; break;
}
age++;
}
System.out.println(liquidation);
}
}

6. The CONTINUE statement


Used only FOR cycles.

Abandons the execution of the body and continues to the next iteration.

Example: Show every year leap of the 21st century.

for (int year = 2001; year < = 3000; year ++) {


if ((year % 100 == 0) & & (year % 400! = 0))
continue;
if (year % 4 == 0)
System.out.println (year);
}
7 EXERCISES

Exercise 1

Show the conversion of 1 to 10 USD in dollars, dollar-to-dollar assuming that exchange rate is 3.30
dollars / dollar.

public class Change {


public static void main (String[]args)
{
int dollar = 1;
while (dollar <= 10)
{
System.out.println (dollar + "dollars =" + dollar * 3.3 + "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?

public class Main{

public static void main (String[]args)


{
double money = 1000;
int month = 1;

while (month <= 12)


{
money = money * 1.02;
month++;
}
System.out.println (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

public class Clock {}


public static void main(String[] args) {}

for (int h = 0; h < = 23; h ++)


for (int m = 0; m < = 59; m ++)
for (int s = 0; s < = 59; s ++)
System.out.println(h +"h"+ m +"m"+ s+"s");
}
}

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

public class Money {


public static void main(String[] args) {
double money = 1000;
int month = 1;

for (;) {
money = money * 1.02;
if (money >= 1500) break;
month ++;
}
System.out.println (month);
System.out.println (money);
}
}

You might also like