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

Post on 28-Dec-2015

238 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Lecture 4Input/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’.

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

Data Types, cont.

Examples of these data types (in MATLAB):

Integer: 47

Float: 39.42

String: ‘My name is Fred’

Data Types, cont.

Making variables with these data types:

Integer: age = 47;

Float: weight = 39.42;

String: name = ‘My name is Fred’;

Data Types, cont.

Data types exist even when the computer generates the value:

Integer: scaleFactor = 24 / 6;

Float: conversionFactor = 5 / 7;

String: x = ???

Input-Output

Embellishing simple problems done before.

7

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;

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.

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

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.

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:’

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?

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?

% 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()

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

In a short example, what are the differences?

17

<enter>

<enter>

<enter>

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

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.

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: >>

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

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…>>

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

>>

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

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

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

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

Operators

Operators are symbols that indicate a task to be performed.

Addition operator: +

Multiplication operator: *

Division operator: /

Power operator: ^

Operators, cont.

Operators can be unary – taking only one operand:

Unary -: y = -x;

Or binary – taking two operands:

Multiplication: y = x * y;

Operators, cont.

Operators work on operands.

Operands can be

Numeric (numbers) 1, 3.5, -47

Logical [Boolean] true, false

Operators, cont.

There are three groups of operators.

First two:

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

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

Note that == and = are DIFFERENT!

is equal

is not equal

Operators, cont.

= Assignment

y = 5 Make y hold the value 5.

== Comparison

y == 5 Does y hold the value 5?

Operators, cont.

Third group: Logical (Boolean) Operators:

Now: Later:

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

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

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

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)

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

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

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

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

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.

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

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.

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

top related