Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1."— Presentation transcript:

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

2 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’.

3 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

4 Data Types, cont. Examples of these data types (in MATLAB): Integer:47 Float:39.42 String:‘My name is Fred’

5 Data Types, cont. Making variables with these data types: Integer:age = 47; Float:weight = 39.42; String:name = ‘My name is Fred’;

6 Data Types, cont. Data types exist even when the computer generates the value: Integer:scaleFactor = 24 / 6; Float:conversionFactor = 5 / 7; String:x = ???

7 Input-Output Embellishing simple problems done before. 7

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

9 Let’s make this script a little more friendly, more user interaction involved.. 9 Area Triangle solver screen base height area keyboard 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.

10 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

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

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

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

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

15 % Collect inputs from the user base_cm = input(‘What is the base in cm? ’); height_cm = input(‘What is the height in cm? ’); % Compute the area of the rectangle area_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.2 What is the height in cm? 4 6.4000 We cannot control the number of decimal places using disp()

16 How do we display with a specific format? There are multiple ways to display the value of a variable 1. Use the semicolon appropriately 2. use the disp() function 3. use the fprintf() built-in function Each is used for specific reasons 1. Debugging – finding problems with the code 2. Simple programs, simple results (your own use) 3. Formatted (“pretty”) output 16

17 In a short example, what are the differences? 17

18 Building the fprintf() command 1. 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

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

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

21 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

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

23 Escape sequences can also be used inside the format string: \nNewline \ttab >> fprintf('%s''s age:\t\t%d years old\n\n', name, age); Fred's age:47 years old >>

24 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 value TOTAL width to occupy # decimal places

25 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

26 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

27 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

28 Operators Operators are symbols that indicate a task to be performed. Addition operator:+ Multiplication operator:* Division operator:/ Power operator:^

29 Operators, cont. Operators can be unary – taking only one operand: Unary -:y = -x; Or binary – taking two operands: Multiplication:y = x * y;

30 Operators, cont. Operators work on operands. Operands can be Numeric (numbers)1, 3.5, -47 Logical [Boolean]true, false

31 Operators, cont. There are three groups of operators. First two: 1.Arithmetic:+, -, *, /, ^ 2.Relational:, =, ==, ~= Note that == and = are DIFFERENT! is equal is not equal

32 Operators, cont. =Assignment y = 5Make y hold the value 5. ==Comparison y == 5Does y hold the value 5?

33 Operators, cont. Third group:Logical (Boolean) Operators: Now:Later: && (logical AND)& (element-wise AND) || (logical OR)| (element-wise OR) ~ (logical NOT)~ (element-wise NOT)

34 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)

35 Operators, cont. TypeInput valuesOutput values Arithmetic: Numbers Numbers e.g. 5 * 315 Relational:NumbersLogical e.g. 5 < 3false Boolean:LogicalLogical e.g. ~truefalse

36 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

37 Operators, cont. &&Logical AND X && Yyields true iff both X and Y are true e.g. (3 =8) true (x 5) false x = 0; (x==0) && (x==-x) true

38 Operators, cont. ||Logical OR X || Yyields true if either X or Y (or both) are true e.g. (3 =8) true x = 4; (x 5) false

39 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 b 2 - 4ac is negative. Conditionals allow the programmer to choose when code will be executed.

40 Conditionals, cont. You’ve already seen one form: if if (b*b-4*a*c < 0) fprintf(‘Imaginary roots’); else r1 = (-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

41 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: 9 The expression to the left of the equals sign is not a valid target for an assignment.

42 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 else yet_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


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

Similar presentations


Ads by Google