lecture 4 input/output conditional statements 1. data types 2. input/outputs 3. operators 4....

42
Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Upload: brooke-lambert

Post on 28-Dec-2015

229 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Lecture 4Input/Output

Conditional Statements

1. Data Types

2. Input/Outputs

3. Operators

4. Conditionals

1

Page 2: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

1. Data Types

Information (“data”) comes in different formats.

We organize the data by describing it with names like “integer” or “string”. These descriptions are called the ‘data types’.

Page 3: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Data Types, cont.

For now, we will discuss only three fundamental data types:

whole numbers: integer

numbers with a fractional portion: floats

groups of characters: strings

Page 4: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Data Types, cont.

Examples of these data types (in MATLAB):

Integer: 47

Float: 39.42

String: ‘My name is Fred’

Page 5: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Data Types, cont.

Making variables with these data types:

Integer: age = 47;

Float: weight = 39.42;

String: name = ‘My name is Fred’;

Page 6: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Data Types, cont.

Data types exist even when the computer generates the value:

Integer: scaleFactor = 24 / 6;

Float: conversionFactor = 5 / 7;

String: x = ???

Page 7: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Input-Output

Embellishing simple problems done before.

7

Page 8: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Pb1 solved a long long time ago.

The I/O diagram where the values used for calculation are present in the program:

8

Area Triangle solver

base

screen

height

area

No external interface on the input side means that the values of base and height are hard-coded in the script.

External interface on the output side means that the value of area is displayed on the screen

base

height

base = 30.2;height = 20.3;

Page 9: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Let’s make this script a little more friendly, more user interaction involved..

9

Area Triangle solver screen

base

heightareakeyboard

External interface on the input side means that the values of base and height is given by someone on the keyboard. (No longer hardcoded)

No change on that side, area is still shown on the screen.

Page 10: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

How do we ask for input?

There are built-in functions to get information from the user.

These functions typically ask the programmer to supply prompts to clue the user on what is being sought.

General form: var = input(prompt) Two examples are given:

num_apples = input('How many apples');name = input('What is your name', 's');

10

Page 11: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

What data types are we asking from the user?

num_apples = input('How many WHOLE apples:');name = input('What is your name', 's');

In the first statement, we are asking the user to provide a number – specifically an integer.

In the second statement, we are asking the user to provide a sequence of characters – i.e. a string.

Page 12: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

The input() function has two different forms:

In the first form, there is only the prompt inside the parentheses:

num_apples = input('How many WHOLE apples:');

We say there is only one argument to the function. Arguments are inputs to the function – information being sent into the function so it can do its job.

The one argument is the prompt string:‘How many WHOLE apples:’

Page 13: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

In the second form of the input() function, there are TWO arguments: the prompt string, and another string: ‘s’

name = input('What is your name', 's');

The second argument is information telling the input() function to expect a string from the user. If this string is present, it must be ‘s’.

Why does it matter whether the computer thinks the user is providing a string or a number? Can’t it tell?

Page 14: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

So..

Let’s code that triangle problem:

Our triangle program requires two values: a base and a height for the triangle.

Collect them from the user:base_cm = input('What is the base in cm? ');

height_cm = input('What is the height in cm? ');

14

Notice the space… why is it there?

Page 15: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

% Collect inputs from the userbase_cm = input(‘What is the base in cm? ’);height_cm = input(‘What is the height in cm? ’);

% Compute the area of the rectanglearea_cm2 = 0.5 * base_cm * height_cm;

% Display the answer on the screen% ??? How do we show the output?disp(area_cm2);

Not very pretty:What is the base in cm? 3.2What is the height in cm? 4 6.4000

We cannot control the number of decimal places using disp()

Page 16: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

How do we display with a specific format?

There are multiple ways to display the value of a variable

1. Use the semicolon appropriately2. use the disp() function3. use the fprintf() built-in function

Each is used for specific reasons1. Debugging – finding problems with the code2. Simple programs, simple results (your own use)3. Formatted (“pretty”) output

16

Page 17: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

In a short example, what are the differences?

17

<enter>

<enter>

<enter>

Page 18: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Building the fprintf() command1. fprintf() % is the built-in function

2. fprintf(, variables to print are inserted at the end separated by commas)

3. fprintf(‘string inserted here’,variables at the end)

% the format string allows you to put words, use format codes (placeholders).

4. fprintf(‘within the string, insert placeholders’,)

% the placeholders allow the command to place the actual values in a specific

% format and location. Use the following placeholders depending on the data

% type of the variable(s)

18

Page 19: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Placeholders – codes to use values in variables

Why do we need them?

Suppose we have a variable, x, that holds some value. Let’s further suppose it holds a float.

How do we get the program to print the value in the variable? Remember – we (the programmer) may not know what value is in it. It may be computed during the running of the program.

Page 20: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Can we just say this?

fprintf('The value in x is: x\n');

Nope:>> fprintf('The value in x is: x');The value in x is: x

How about this?fprintf('The value in x is: ', x);

Nope:

>> fprintf('The value in x is: ', x);

The value in x is: >>

Page 21: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

What we need is some way to tell the fprintf() function that we don’t want to print the letter ‘x’, but we want print the value stored in the variable x.

Placeholders to the rescue!

fprintf(‘The value of x is: %f’, x);

“function call”

“format string”

“placeholder”(part of format string)

variable to be printed

Page 22: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Printing with multiple values:

Match up placeholder with variable, left to right:name = input(‘Your name? ’, ‘s’);

age = input(‘Your age? ’);

fprintf(‘%d is %s’’s age…’, age, name);

Sample run:Your name? Fred

Your age? 47

47 is Fred’s age…>>

Page 23: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Escape sequences can also be used inside

the format string:

\n Newline

\t tab

>> fprintf('%s''s age:\t\t%d years old\n\n', name, age);

Fred's age: 47 years old

>>

Page 24: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Format Modifiers

Once the placeholder is ready, we can

further change how the values are displayed.

Adding special numbers inside the placeholder will tell fprintf() how exactly to display the value.

Format modifier form: % f-3.2

Left-justify the valueTOTAL width to occupy

# decimal places

Page 25: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Format Modifiers, cont.

So, to display a floating point value to 3 decimal places:

fprintf(‘The value of pi: %-7.3f’, pi);

Output:

The value of pi: 3 . 1 4 2 _ _

Underscores indicate whitespace – they will not actually show in the output. Note there are 7 spaces occupied

Page 26: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Format Modifiers, cont.

When debugging, it can be helpful to “delimit” the output – this lets you see where the “whitespace” is:

fprintf('The value is:\t-->%9.3f<--\n\n', pi);

Output:The value is: --> 3.142<--

>>

The delimiters make it easy to notice the whitespace: spaces, tabs, newlines

Page 27: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Format Modifiers, cont.

Obviously, the decimal place portion of format modifiers will not apply to strings and integers – but the others do!

name = ‘Fred’;

age = 47;

fprintf(‘%-6s is %4d years old!\n’, name, age);

Output:Fred is 47 years old!

Note the spaces

Page 28: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Operators

Operators are symbols that indicate a task to be performed.

Addition operator: +

Multiplication operator: *

Division operator: /

Power operator: ^

Page 29: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Operators, cont.

Operators can be unary – taking only one operand:

Unary -: y = -x;

Or binary – taking two operands:

Multiplication: y = x * y;

Page 30: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Operators, cont.

Operators work on operands.

Operands can be

Numeric (numbers) 1, 3.5, -47

Logical [Boolean] true, false

Page 31: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Operators, cont.

There are three groups of operators.

First two:

1.Arithmetic: +, -, *, /, ^

2.Relational: <, >, <=, >=, ==, ~=

Note that == and = are DIFFERENT!

is equal

is not equal

Page 32: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Operators, cont.

= Assignment

y = 5 Make y hold the value 5.

== Comparison

y == 5 Does y hold the value 5?

Page 33: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Operators, cont.

Third group: Logical (Boolean) Operators:

Now: Later:

&& (logical AND) & (element-wise AND)

|| (logical OR) | (element-wise OR)

~ (logical NOT) ~ (element-wise NOT)

Page 34: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Operators, cont.

Logical operators (aka Boolean operators):

Logical (Boolean) values are true and false

In MATLAB, true and false are keywords

(please notice the case of the letters)

Page 35: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Operators, cont.

Type Input values Output values

Arithmetic: Numbers Numbers

e.g. 5 * 3 15

Relational: Numbers Logical

e.g. 5 < 3 false

Boolean: Logical Logical

e.g. ~true false

Page 36: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Operators, cont.

Logical operators:Take logical values and perform some operation on

them to yield a logic value

~ (Logical NOT):Negates: turns true values into false, and false

values into true.

Example: x = true;y = ~x; % y has the value

false

Page 37: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Operators, cont.

&& Logical AND

X && Y yields true iff both X and Y are truee.g. (3<5) && (8>=8)

true(x< 3) && (x > 5)

false x = 0;(x==0) && (x==-x)

true

Page 38: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Operators, cont.

|| Logical OR

X || Y yields true if either X or Y (or both) are true

e.g. (3<5) || (5>=8)

true

x = 4;

(x< 3) || (x > 5)

false

Page 39: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Conditionals

Conditional statements allow us to write code that does not necessary execute every time the program is run.

Suppose you only want to compute the quadratic roots if the coefficient, a, is not 0. Or you don’t want to compute imaginary roots – those values when b2-4ac is negative.

Conditionals allow the programmer to choose when code will be executed.

Page 40: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Conditionals, cont.

You’ve already seen one form: if

if (b*b-4*a*c < 0)fprintf(‘Imaginary roots’);

elser1 = (-b + sqrt(b*b-4*a*c))/(2*a);r2 = (-b - sqrt(b*b-4*a*c))/(2*a);fprintf(‘r1=%.2f, r2=%.2f\n’, r1, r2);

end

Page 41: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Conditionals, cont.

Note that the condition (aka predicate) is a Boolean expression. The condition of an IF statement MUST evaluate to true or false.

So if you mistype it: if (x=5)When you meant: if (x==5)

You will get an error:??? Error: File: program.m Line: 5 Column: 9The expression to the left of the equals sign is not

a valid target for an assignment.

Page 42: Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1

Conditionals, cont.

General form of the if statement. elseif and else segments are optional – if you don’t need them you don’t have to put them in there.

if (some_condition)some_MATLAB_code

elseif (some_other_condition)more_MATLAB_code

elseyet_more_MATLAB_code

end

Many people forget that the elseif requires its own condition!

On the other hand, many people mistakenly place a condition after the else