PSEUDOCODE. It is a conventional code to represent an algorithm

Similar documents
Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Fundamentals of Programming (Python) Getting Started with Programming

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

CS313D: ADVANCED PROGRAMMING LANGUAGE

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Control Statements: Part 1

Introduction to Java Applications

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Eng. Mohammed S. Abdualal

Operators & Expressions

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Unit 3. Operators. School of Science and Technology INTRODUCTION

Chapter 2 Working with Data Types and Operators

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

3. Java - Language Constructs I

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

cs1114 REVIEW of details test closed laptop period

Course Outline. Introduction to java

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

3. Java - Language Constructs I

BCA-105 C Language What is C? History of C

Unit 1 Lesson 4. Introduction to Control Statements

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

COMP Primitive and Class Types. Yi Hong May 14, 2015

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

VBScript: Math Functions

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

SNS COLLEGE OF ENGINEERING

Ex: If you use a program to record sales, you will want to remember data:

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Declaration and Memory

Full file at

CEN 414 Java Programming

A Look Back at Arithmetic Operators: the Increment and Decrement

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Chapter 2. Elementary Programming

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Chapter 2: Data and Expressions

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics

Chapter 3 Problem Solving and the Computer

b) Use one of your methods to calculate the area of figure c.

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Special Section: Building Your Own Compiler

Chapter 2: Data and Expressions

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Chapter 4 Introduction to Control Statements

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Programming for Engineers Iteration

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Introduction to Programming Using Java (98-388)

Full file at

Section A Arithmetic ( 5) Exercise A

Lecture 3 Tao Wang 1

Java Notes. 10th ICSE. Saravanan Ganesh

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

COP 4516: Math for Programming Contest Notes

Variable and Data Type I

Looping Subtasks. We will examine some basic algorithms that use the while and if constructs. These subtasks include

APS Sixth Grade Math District Benchmark Assessment NM Math Standards Alignment

PROGRAMMING IN C AND C++:

Computer Programming CS F111

Types and Expressions. Chapter 3

CHAPTER 2 PROBLEM SOLVING TECHNIQUES. Mr Mohd Hatta Bin Hj Mohamed Ali Computer Programming BFC2042

C/C++ Programming for Engineers: Working with Integer Variables

Add Subtract Multiply Divide

Mathematics LV 5 (with QuickTables)

Condition Controlled Loops. Introduction to Programming - Python

Math Glossary Numbers and Arithmetic

DEPARTMENT OF MATHS, MJ COLLEGE

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Object Oriented Programming with Java

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

Intro to Computational Programming in C Engineering For Kids!

19 Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Building Java Programs

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

ENGR 101 Engineering Design Workshop

Control Statements. Musa M. Ameen Computer Engineering Dept.

Variable and Data Type I

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Loops / Repetition Statements

Chapter 4: Basic C Operators

Scheme of work Cambridge International AS & A Level Computing (9691)

Review for Test 1 (Chapter 1-5)

REPETITION CONTROL STRUCTURE LOGO

ECE 122 Engineering Problem Solving with Java

Chapter 2: Data and Expressions

Chapter 2 ELEMENTARY PROGRAMMING

Information Science 1

Operators. Java operators are classified into three categories:

In this chapter you ll learn:

Transcription:

PSEUDOCODE It is a conventional code to represent an algorithm

PSEUDOCODE It is a conventional code to represent an algorithm

PSEUDOCODE NOTATION Refers the syntax used to write an algorithm in pseudocode

PSEUDOCODE NOTATION Start an algorithm Algortihm NameOfTheAlgorithm { Finish an algorithm }

Data Types Primitives Data Objects Data Integer number int String (collection of chars) String Real number (Floating point) double Character (single alphanumeric symbol) char Boolean data (FALSE/TRUE) boolean

Data Types Default values int 0 double 0.0 char boolean FALSE String null Char values should be shown between String values should be shown between

Variable Is an abstract field which represent a storage location with a particular name. Physical storage location Abstract Field Is a reference of

Variable Different types of data could be stored in variables. Those data could change their value depending of different operations done with them 45 Data stored * 2 90

Naming a variable Is convenient to label the storage location with a name: Variable names are letters (A..Z, a..z) combined with decimal digits (0..9) and the underline symbol (_) No length limits No allowable special symbols (#$%&/()[]{}.,;! ) Variable names are case sensitive Variable names are all capitals, for example, CITY Self-documented names

Assigning values To store a value in a variable, the assignment operation should be done: Values will be assigned using =, for example: AGE=35 FIRSTNAME_OF_CLIENT= Fernando STATUS=TRUE GENDER= F AREAOFCIRCLE=56.2345

Assigning values Naming a variable AGE AGE Assigning a value 45 AGE = 45

Creating a variable To create the abstract field and the storage location of a variable, a declaration sentence has to be executed. This operation should be done previously to start using the variable Declaration syntax: Assignment operation Data type variable_name = value ; Sentence separator Type of the data to be stored Name of the variable Value to be stored

Output information Operation that indicates data is output in an output device: printer, screen, Output syntax: output ( Prompt ); The label is shown in an output device output (variable); The content of the variable is shown an output device output ( Prompt + variable); The label and the content of the variable is shown in an output device output ( Label + variable); + in this context is called concatenation operator, and it means link the label and the variable value

Example Problem: Given the value of a temperature in Celsius degrees, calculate the equivalent Fahrenheit degrees value Algorithm TemperaturesConvertion { double CELSIUS=0.0; double FAHRENHEIT=0.0; CELSIUS=37; FAHENHEIT=(9/5)*CELSIUS+32; output (CELSIUS+ C are equivalent to +FAHRENHEIT+ F ); }

Input Data Operation that permits to capture data from an input device and stores it in a variable. There are different instructions to input data for every data type. Input syntax: inputstring(string prompt); to get a String value inputint(string prompt); to get an integer value inputdouble(string prompt); to get a double value inputchar(string prompt); to get a char value inputboolean(string prompt); to get a boolean value

Example Problem: Given the value of a temperature in Celsius degrees, calculate the equivalent Fahrenheit degrees value Algorithm TemperaturesConvertion { double CELSIUS=0.0; double FAHRENHEIT=0.0; CELSIUS=inputDouble( Type the temperature in Celsius degrees ); FAHENHEIT=(9/5)*CELSIUS+32; output (CELSIUS+ C are equivalent to +FAHRENHEIT+ F ); }

Operators Are symbols to establish an arithmetic, logic or relational operations between data Arithmetic Operators: Relational Operators: Logic operators: + - * / % > >= < <= ==!= &&!

Arithmetic Operators Operator Computes Syntax Category + the sum of its two operands - subtracts the second operand from the first * the product of its operands / % divides its first operand by its second operand the remainder after dividing its first operand by its second a + b a - b a * b a / b a % b Additive Additive Multiplicative Multiplicative Multiplicative

Relational Operators Operator Computes Syntax Category > Greater than a > b Relational >= Greater than or equals to < Less than <= Less than or equals to a >= b a < b a <= b Relational Relational Relational == Equals to a == b Relational!= Is not equal to a!= b Relational

Logical Operators Operator Computes Syntax Category && P1 && P2 Are both values TRUE? Logic Is, at least, one value TRUE?! Is the opposite logical value P1 P2!P1 Logic Logic

Operators Precedence Category Operator Asociativity Postfix ( ) Left to Right Unary! Right to Left Multiplicative * / % Left to Right Additive + - Left to Right Relational < <= > >= Left to Right Equality ==!= Left to Right Logical AND && Left to Right Logical OR Left to Right Assignment = Right to Left

Functions Are pre-designed formulas to execute particular and complex calculations sqrt(value) calculates the square root of a value pow(base,power) calculates the result of an exponential expression xx yy abs(value) calculates the absolute value of a quantity : :

Exercise In an University, the final grade of a subject is calculated by the weighted average of three grades. The weights of the grades are given as percentages respectively: 20% to the first grade, 25% to the second grade and 55% to the third one, respectively. Develop an algorithm, in pseudocode, which takes the personal information of any student and calculate the final grade of a subject.

Exercise La instalación de criaderos de peces, en una zona rural del Valle del Cauca, exige la compilación de ciertos datos relacionados con los pescados que allí van a sembrarse: la especie, la talla (el largo del pez) y el peso, serán características que en cada criadero se determinarán mediante sensores especiales de tecnología de control. Implementar un algoritmo registre y calcule los datos necesarios para dar una información eficaz de cualquier pez. El factor de densidad lineal es un valor que permite generalizar y calcular el peso, dado solamente el tamaño y que en este caso será 1.75.

CONTROL FLOW STATEMENTS Break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code

CONDITION Is an expression which involves relational and/or logic operators. A boolean value is the result of a condition evaluation Examples: AGE >=35 AREA<23.7 AND SHAPE= CIRCLE Tip: relational operators: > < >= <= == Logic operators: AND OR NOT

if then STATEMENT It tells your algorithm to execute a certain section of code only if a particular test, of a condition, evaluates to true Syntax if (condition) then sentences for TRUE value; endif

if then STATEMENT Example: A web site has implemented a routine that gives the access to its content only if the user type an appropriate password. Implement an algorithm to solve this situation Algorithm AccessGranted{ String PASSW= AZ123b, PASSUSER=null; PASSUSER=inputString( Type the password ); if (PASSUSER=PASSW) then output( Welcome to the web site ); endif }

if then else STATEMENT The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false Syntax if (condition) then sentences for TRUE value; else sentences for FALSE value; endif

if then STATEMENT Example: A web site has implemented a routine that gives the access to its content only if the user type an appropriate password; in other case a pop up window will notices the wrong password. Implement an algorithm to solve this situation Algorithm AccessGranted{ String PASSW= AZ123b, PASSUSER=null; PASSUSER=inputString( Type the password ); if (PASSUSER=PASSW) then output( Welcome to the web site ); else output( Access hasn t be granted!!! ); endif }

EXERCISES Problem 1: Write an algorithm that recommends the number of calories a person should eat each day. Calories are units of energy found in all foods. Base your recommendation on the person's weight and whether the person has an active or sedentary (inactive) lifestyle. If the person is sedentary, that person's activity factor is 13. If the person is active, that person's activity factor is 15. Multiply the activity factor by the person's weight to get the recommended number of calories Problem 2: A code program to detect and advertise when a driver exceeds speed limits is required to be burned in a ROM memory and to be installed in a special device which will be used by the highway police. Develop a pseudocode of the algorithm to sketch the real program. Problem 3: Given a natural number, determine if it is an odd or even number Problem 4: Given two natural numbers A and B, determine if B is divisor of A

NESTED CONTROL FLOW STATEMENTS Consist of the combination or the link of two or more control flow statements to increase the functional power of an algorithm NESTING IF THEN ELSE STATEMENTS Syntax if (condition1) then sentences for TRUE value of condition 1; else if (condition2) then sentences for TRUE value of condition 2; else if (condition3) then sentences for TRUE value of condition 3; else if.. else sentences for FALSE value all conditions; endif

if then STATEMENT Example: Classify a triangle given the three sides length Algorithm Triangles { double SIDEA=0.0, SIDEB=0.0, SIDEC=0.0; SIDEA=inputDouble( Length of side A ); SIDEB=inputDouble( Length of side B ); SIDEC=inputDouble( Length of side C ); if (SIDEA==SIDEB AND SIDEB==SIDEC) then output ( Equilateral triangle ); else if (SIDEA==SIDEB OR SIDEA==SIDEC OR SIDEB==SIDEC) then output ( Isosceles triangle ); else output ( Scalene triangle ); }

EXERCISES Problem 1: Write a program to determine the cost of an automobile insurance premium, based on driver's age and the number of accidents that the driver has had. The basic insurance charge is $500. There is a surcharge of $100 if the driver is under 25 and an additional surcharge for accidents: # of accidents Accident Surcharge 1 50 2 125 3 225 4 or more No insurance

EXERCISES Problem 2: Windows performs a date format in two ways: a short format which shows the date as mm / dd / yyyy; and a long format mmmm-dd-yyyy September-11-2013 (long format), 9/11/2013 (short format) Implement an algorithm, in pseudocode, that permits to convert a format date from short to long format

EXERCISES Problem 3: El personal que acude a un gimnasio deportivo se puede clasificar en socios o en invitados. El gimnasio cobra una tarifa fija por hora (no se cobran fracciones de la hora), pero para los socios hay un descuento del 20 % del valor a pagar. Además, para fomentar el ejercicio físico en adultos mayores, el gimnasio ofrece un descuento adicional del 10% del valor a pagar, a todas las personas con edad de 40 o más años. Desarrollar el algoritmo en pseudocódigo que permita calcular el valor a pagar por la utilización del gimnasio, de una persona cualquiera

EXERCISES Problem 4: Given the Cartesian coordinates of a point P (x, y), calculate Polar coordinates of P (r, θ) Given the polar coordinates of a point P (r, θ), calculate Cartesian coordinates of P (x, y) Use the following information

FLOW CHART It s a graphic data representation of an algorithm. Symbols: Perform a Task Start End Decision Manual Input Documentt Display

Example Start CELSIUS=0.0 FAHRENHEIT=0.0 Problem: Given the value of a temperature in Celsius degrees, calculate the equivalent Fahrenheit degrees value CELSIUS=inputDouble( Type the temperature in Celsius degrees ) Algorithm TemperaturesConvertion { double CELSIUS=0.0; double FAHRENHEIT=0.0; CELSIUS=inputDouble( Type the temperature in Celsius degrees ); FAHENHEIT=(9/5)*CELSIUS+32; output (CELSIUS+ C are equivalent to +FAHRENHEIT+ C ); } FAHENHEIT=(9/5)*CELSIUS+32 output (CELSIUS+ C are equivalent to +FAHRENHEIT+ C ); End

while loop STATEMENT The while statement continually executes a block of statements while a particular condition is true Syntax loop while condition statements; end loop Condition NO YES Statements

while loop STATEMENT Example: Print the first 5 even numbers out Algorithm Serie1 { int COUNTER=1; loop while COUNTER < 5 output(counter*2+ \n ); COUNTER=COUNTER+1; end loop }

while loop STATEMENT Example: Print the first 5 even numbers out Algorithm Serie1 { int COUNTER=1; loop while COUNTER < 5 output(counter*2+ \n ); COUNTER=COUNTER+1; end loop } COUNTER variable is a loop counter A loop counter is a variable that increments or decrements its value with a fixed quantity

while loop STATEMENT Example: Print the following series numbers: 300, 250, 200, 150, 100, 50, 0 Algorithm Serie2 { int COUNTER=300; loop while COUNTER > -1 output(counter+ \n ); COUNTER=COUNTER-50; end loop }

while loop STATEMENT Example: Determine the final printing of the following algorithm Algorithm Serie1 { int COUNTER=0, NUMBER=0, ACUM=0; loop while COUNTER < 4 NUMBER=inputInt( Type a natural number ); ACUM=ACUM+NUMBER; COUNTER=COUNTER+1; end loop output( The result is +ACUM); }

while loop STATEMENT Example: Determine the final printing of the following algorithm Algorithm Serie1 { int COUNTER=0, NUMBER=0, ACUM=0; loop while COUNTER < 4 NUMBER=inputInt( Type a natural number ); ACUM=ACUM+NUMBER; COUNTER=COUNTER+1; end loop output( The result is +ACUM); } ACUM variable is a loop accumulator A loop accumulator is a variable that increments or decrements its value with a variable quantity

while loop STATEMENT Loop counter and loop accumulator operators: N++ is equivalent to N=N+1 N-- is equivalent to N=N-1 N+=c is equivalent to N=N+c N-=c is equivalent to N=N-c N*=c is equivalent to N=N*c N/=c is equivalent to N=N/c Loop counter If c is a constant value N is a loop counter If c is a variable value N is a loop accumulator

while loop STATEMENT TRACE TABLE is a table used to test an algorithm by tracing the values of its variables during the algorithm flow Variable 1 Variable 2 Variable 3 output value value value value value value value value value value value value

while loop STATEMENT Example: Determine the final printing of the following algorithm Algorithm Serie1 { int COUNTER=0, NUMBER=0, ACUM=0; loop while COUNTER < 4 NUMBER=inputInt( Type a natural number ); ACUM=ACUM+NUMBER; COUNTER=COUNTER+1; end loop output( The result is +ACUM); } Trace Table COUNTER NUMBER ACUM OUTPUT 0 0 0 1 5 5 Type a natural number 5 2 2 7 Type a natural number 2 3 6 13 Type a natural number 6 4 3 16 Type a natural number 3 The result is 16

while loop STATEMENT Exercises: 1. Print a sequence of asterisk characters depending of a given value 2. Read and print values entered by a user until a particular sentinel value is encountered. Do not print the sentinel value. Assume the sentinel value is stored in a constant called SENTINEL. 3. Print the numbers between LOW and HIGH that are evenly divisible by four but not by five. 4. Given a natural number, determine if it is a perfect number 5. Generate the Fibonacci numbers

from/to loop STATEMENT Syntax loop counter from counter initial value to counter final value statements; end loop counter declaration statements counter increasing/decreasing Condition (involving the counter) NO YES

from/to loop STATEMENT Example: Write and algorithm in pseudocode to calculate the average of the students ages in a certain classroom Algorithm TheAverage { int QUANTITY=0, COUNTER=0, ACUM=0, AGE=0; QUANTITY=inputInt( Type the quantity of students ); loop COUNTER from 1 to QUANTITY AGE=inputInt( Type the age ); ACUM += AGE; end loop output ( The average is +(ACUM/QUANTITY)); }

from/to loop STATEMENT Example: Given a quantity of natural numbers, compute the sum of the odd numbers between 1 and the final number Algorithm SumOdd{ int QUANTITY=20, COUNTER=0; acum=0; QUANTITY=inputInt( Type the amount of numbers ); loop COUNTER from 1 to QUANTITY if(counter mod 2 0) then ACUM += NUMBER; end if end loop output ( The sum is +ACUM); }

from/to loop STATEMENT Exercises: 1. Given a positive integer number, calculate its factorial 2. Write a program called HarmonicSum to compute the sum of a harmonic series, as shown below, where n=50. 3. Write a program called ComputePI to compute the value of π, using the following series expansion. You have to decide on the termination criterion used in the computation (such as the number of terms used or the magnitude of an additional term). Is this series suitable for computing π?

loop STATEMENTS 4. Write an algorithm in pseudocode to find out if a number is prime 5. Develop the trace table to the following algorithm: Algorithm Special { int N=0,M=0; N=inputInt ( Type a positive integer number ); loop while N>0 N/=10; M++; end loop output ( Value +M); }

Approved notation for developing pseudocode http://occ.ibo.org/ibis/documents/dp/gr5/computer_science/d_4_coms c_sup_1201_1b_e.pdf International Baccalaureate Organization 2012 IB Java Examination Tool Subset (JETS) http://occ.ibo.org/ibis/documents/dp/gr5/computer_science/d_4_coms c_sup_1201_1a_e.pdf http://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html http://visualbasic-dotnet-hindi.blogspot.com/2013/01/control-flowstatements.html