0% found this document useful (0 votes)
2 views20 pages

NoteSet_2_v1

Uploaded by

lianchu517
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views20 pages

NoteSet_2_v1

Uploaded by

lianchu517
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 20

Note Set (NS) #2: Programming Concepts

Conditional Statements: if Statements


Contents
Section 1: Conditional Statement Foundation .............................................................................................. 1
1.1 if-end Statements ........................................................................................................................ 1
1.2 if-else Statements ........................................................................................................................ 3
1.3 if-elseif-else Statements .............................................................................................................. 5
Section 2: Multiple Conditions Required ...................................................................................................... 8
2.1 Multiple Conditions: and .................................................................................................................... 8
2.2 Multiple Conditions: or ..................................................................................................................... 10
2.3 Boolean Logic .................................................................................................................................... 11
2.4 User Inputs ........................................................................................................................................ 13
Section 3: Examples and Exercises .............................................................................................................. 16

Section 1: Conditional Statement Foundation

1.1 if-end Statements

• The word if is arguably the most important word in programming. But before
we jump into coding, let’s think about real-world examples of the word.

• Imagine we are playing a game where the rules are simple:


o If I stomp my feet, you clap your hands. That’s it.
o What does this mean? Well, you will watch me and wait around until I
stomp my feet. If I don’t stomp my feet, you won’t do anything with
your hands.
o When I eventually stomp, you will follow the rules and clap.

• An if statement follows the same type of rules, as shown in Figure 1.


o If a condition is met (i.e., the condition is true), then the code within the
if statement will run.
▪ “Within” implies the block of code between the words if and end.
▪ Note that this if/end pair is not necessarily true for all
programming languages (sometimes the statement only requires
if and notices tabs to see when the block of code ends).

1
o The word if tells the software that you are beginning this conditional
statement.
o The line immediately after the word if is the condition, i.e., the thing
that needs to be true to move into the block of code.
▪ If that condition isn’t met, the software will ignore everything
within the block.

o So, to summarize Figure 1:


▪ If feet are stomped, enter the block of code, and do what is inside
(clap your hands).

Figure 1: An if statement for the game.

• A simple example of this is shown below, where we check if a number is


negative.
o We define x to be a number.
o We write if to begin the statement.
o The associated condition is x < 0.
▪ In words, this line says “if x is less than 0, run this block of code”.
o In this case, if x is negative, we will display the phrase x is Negative in
the Command Window (this is what disp does).

o What happens if the condition isn’t met?


▪ Well, nothing. Since the condition isn’t met (maybe x = 100
instead), we wouldn’t enter the block, and nothing will appear in
the Command Window.

2
x = -4;
if x < 0
disp('x is Negative') %displays in Command Window
end

• Perhaps we want to do other tasks in addition to displaying the fact that x is


Negative.

• Below is a modified code where we change the sign of x to be positive if it is


originally negative.
o The moral is that the block of code can be as long as you want: anything
within if and end is the code executed if the original condition is true.

x = -4;
if x < 0
disp('x is Negative') %displays in Command Window
x = -1*x; %makes x into a positive number
end
disp(x) %displays the final value of x, which is always > 0

• Note that the disp function will display words when enclosed by apostrophes.
o If there are no apostrophes (like the last line), then it will display the
value of the variable.
o If that variable doesn’t exist, there will be an error.

1.2 if-else Statements

• The if-end statements described in the previous section are fairly limited: it
only checks if something is true and responds accordingly.

• What if we care about whether something is true or false?


o Then, we will use an if-else statement, where a separate block of code
is used in case the condition isn’t met.
• Below is the same example checking for whether a number is negative, but
we included an else statement as well.
o The general chain of progression is shown in Figure 2.

3
x = 7;
if x < 0
disp('x is Negative')
else
disp('x is Positive')
end

Figure 2: If-Else statement for the example presented above.

• Note that the word else does not exist on its own: it needs the word if to work
properly.
o Additionally, despite the fact we have more scenarios, we only require
one end statement.

• Is there a value of x where the code will not perform as expected? More on
this after the following example.

Example #1

• Greg wants to save $300 to buy a Nintendo Switch at the end of 4 weeks.
• His paycheck each week is $100.
o When he gets paid, the government takes out 25% of his paycheck,
i.e., he can save 75% for each paycheck.
• Write a code to test out if we will succeed in saving the money.

• First, let’s define some variables.


o His check amount.
o How much he saves per week (after taxes).
o Number of weeks we are saving within.

4
check_amount = 100; %weekly total
savings_oneWeek = 0.75*check_amount; %weekly savings
weeks = 4; %number of weeks

• How much will he make in total after 4 weeks?


o It will be weeks*savings_oneWeek

check_amount = 100; %weekly total


savings_oneWeek = 0.75*check_amount; %weekly savings
weeks = 4; %number of weeks

if weeks*savings_oneWeek >= 300 %is total >= 300?


disp('Success! Saved enough!')
else
disp('Sorry, can''t buy it yet :( ')
end

• Note: the display command uses characters (which we will discuss in


NS#7).
o Characters involve single quotations.
o To actually use a quotation (like in the word can’t), we type the single
quotation twice.
▪ Weird rule, but that’s what we do to overcome the fact that
single quotes are reserved for something else.

1.3 if-elseif-else Statements

• Below is a copy/paste version of the code we wrote earlier to see if a number


is positive or negative.

x = 7;
if x < 0
disp('x is Negative')
else
disp('x is Positive')
end

5
• What value of x will make this code output an incorrect statement?
o Well, if x = 0, the Command Window will say that this is a positive
number…but this isn’t true since 0 does not have an affiliated sign.
o Is there a way to account for this?

• This is where we include another possibility for our if statement, in the form
of elseif.
• Including this line (or several of these lines) allows for multiple conditions.
The modified code below illustrates this.

x = 4;
if x < 0
disp('x is Negative')
elseif x > 0 %elseif requires a condition written after
disp('x is Positive')
else %else does not require a condition
disp('x is 0')
end

• The general procedure is:


o We define x.
o The first statement checks if x is negative.
▪ If this fails, we move onto the next statement.
o The second statement checks if x is positive.
▪ If this fails, we move onto the next statement.
o The final statement is else, which considers all other cases not described
in the previous if and elseif conditions.

• The most important thing to note about this is that if we have an if


statement tied to elseif and else statements, only one of them can run.
o If multiple are true, the first one encountered will be satisfied and the
rest will be ignored. This is shown below with an example.
▪ Also note that even if we encounter the first true condition and
don’t look at the others, MATLAB will produce an error if the
conditions are written incorrectly.

6
z = 7;
if z < 10
disp('z is less than 10')
elseif z > 0
disp('z is positive') %this will not display for z = 7
end

• However, if we wrote the above as two separate if statements, then both


sentences will be displayed.
o Note that we would need an additional end statement since we have
stated a brand-new condition in this case that is unrelated to the first
condition.

z = 7;
if z < 10
disp('z is less than 10')
end

if z > 0
disp('z is positive')
end

Example #2

• To really stress the point of if-elseif-else statements, we will do a simple


example.
o Is x equal to a certain value?

• The thing to remember:


o if and else-if check for specific conditions
o else checks for everything else that hasn’t been discussed, so a general
check. Nothing should come after else in a code. You may get errors
or incorrect solutions.

7
x = 7;
if x == 4 %first specific check
disp('x = 4')
elseif x == 6 %additional specific check
disp('x = 6')
elseif x == -3 %additional specific check
disp('x = -3')
else %everything ELSE that wasn't asked yet
disp('x is NOT 4, 6, or -3');
end

• In the code above, we are checking if x is 4, 6, or -3.


o These are specific checks, so we use if and elseif to do so.
o We include an else statement for everything ELSE that hasn’t been
specified.
▪ This isn’t specific. It’s general and essentially says “nothing
before me was satisfied; therefore, I am.”

Section 2: Multiple Conditions Required

• Section 2 will discuss MATLAB implementation of items discussed in Section


1, along with some more important pieces of information to elevate what
we’ve already learned.

• We will begin this section by discussing the implementation of if-like


statements in MATLAB, as well as incorporating multiple conditions into
executing the block of code.
o After, we will see how MATLAB handles Boolean logic, i.e., true or
false statements, in a different way.

2.1 Multiple Conditions: and

• What if you want to only run a code if multiple conditions are true?
o Maybe you’re running a code that designs the width of a cantilever
beam.
o You need to ensure that the beam does not exceed its maximum stress
(i.e., it breaks) AND that it doesn’t exceed the cost of material.
o You provide a width value, run the code, and see the results if both
conditions are met.

8
o So, how do we do this?

• To execute this concept, we will use && to tie two conditions together.
o For example, Figure 3 shows a code where we have two variables x and
y and we want to check if they are both positive.
o We would say (in words): “if x is greater than 0 AND y is greater than
0, then say that they are both positive.”
▪ Else, display that at least one variable isn’t.

Figure 3: Example of using an if statement for two conditions.

• This may be extended to any number of conditions with && signs appearing
after each condition. This is shown below in Figure 4.

Figure 4: Multiple and conditions. If any one of them fail, then the entire statement is considered false.

9
2.2 Multiple Conditions: or

• The other type of statement we may be interested in is or, where if we have


two conditions, we will execute the code if at least one of them is true.
o For example, perhaps you are taking your last semester of classes
before graduation. All the classes are pass/fail, i.e., you can get either
an A or an F in the class.
o In order to graduate, you need an A in at least one of the classes.
o Assume you are taking two classes: Math and English.
o What are the possibilities to graduate? There are four combinations.

A, A
A, F
F, A
F, F

o Which allow you to graduate?


▪ Well, any of the top three cases since you received an A in at least
one class.
o How do we word this properly?
▪ “If I get an A in math OR I get an A in English, I will graduate.”

• How do we code this? Similar to earlier, the if statement will be typed, but we
use two vertical bars in MATLAB to signify or.
• This is shown in Figure 5, where the | | bars are located above the Enter key
on your keyboard (hold shift to access them).

10
Figure 5: The or command using ||.

2.3 Boolean Logic

• So, what is happening with MATLAB when you use an if/or type of code?
o MATLAB is checking whether a condition is true or false, but how?

• The conditional cases that we are interested in examining will output a 1 or


a 0.
o A simplified version of this is shown below, where the if command is
looking to see if the following value is 1 or not.
▪ If it sees a 1, the condition is met and the code is executed.

if 1
disp('True condition')
end

o Each of the operators we have seen so far (<, >, >=, etc.) secretly output
a one or zero.
o For example, if you wanted to compare the numbers 3 and 4, you will
see the associated responses in Figure 6.
11
• The concept of using 1’s and 0’s is called Boolean Logic or Boolean Algebra.

Figure 6: Left: The output of a true statement is 1. Right: The output of a false statement is 0

• One type of condition that we haven’t discussed is the concept of equality, i.e.,
if two things are equal, execute the code.

• As described in NS#1, the equal sign is used for assigning one expression to
a variable. This command does not output a 1 or 0 for checking equality.
o The code below would produce an error since the if statement is
checking for a one or zero. The single equal sign does not do this.

x = 1;
y = 1;
if x = y %this line is problematic!
disp('x and y are equal')
end

• Instead, we will use two equal signs to ask MATLAB to compare two
values. Below is the fixed version of the code above.

12
x = 1;
y = 1;
if x == y %this is correct now
disp('x and y are equal')
end

• Table 1 shows different types of conditions that can be tested.

Table 1: Various Boolean operators.

Condition Syntax in MATLAB


Greater than >
Greater than or equal to >=
Less than <
Less than or equal to <=
Equal to ==
Not equal to ~=
And &&
Or ||

• The other condition is the not equal to command, where we run the code if
two expressions are not equivalent. We write this as a tilde sign (~), followed
by an equal sign (this symbol is located below your Escape Key on the top
left of your keyboard, assuming you have a standard keyboard).
o The code below provides an example.

x = 1;
y = 2;
if x ~= y %not equal command
disp('x and y are NOT equal')
end

2.4 User Inputs

• Something unrelated to if statements but is worth introducing in this Note


Set is how to interact with a user.

13
• For example:
o Let’s say you want to write a code where a student can test what letter
grade they receive.
o The student knows their percentage grade (e.g., they received a 86%
in the class) but they haven’t checked the syllabus and do not know
whether this is an A.
o You send them the code and the code asks them to supply their grade.
Once supplied, the code will run and produce an output.

• The command for this is input, where you will type this word in your code
followed by what you want the user to see. Below is an example.

x = input('The value of x you want to use is: ');

• If you ran this statement, the Command Window will look like Figure 7.
o Note that the code is now paused and waits for the user to type
something in and click enter.
o After clicking enter, the variable x is now defined and you can do
whatever you would like with it.

Figure 7: Using the input function, where the code is paused until the user types in a number.

• Below in Figure 8 is another example using the input command, where we


are asking for the user to supply a number in feet and we will convert it to
inches.

14
Figure 8: An example of asking the user for a number and then using it for another operation.

15
Section 3: Examples and Exercises

Exercise 3.1: Multiple Choice

1) What does the following code output in the Command Window?

x = 3;
y = 6;
if x == y
z = x;
elseif x ~= y
z = y+x;
end
disp(z)

a) 3
b) 6
c) z
d) 9
e) 12
f) Error

2) What does the operator = do?

a) Variable assignment
b) Boolean operator for equality
c) Not equal to
d) Or

3) There are four errors in the code below. What are they?

if pressure = 10
disp(pressure is high)
else
disp(pressure)

16
4) What does the following code output in the Command Window?

g = 4;
h = 28;
if h/g > 7
disp('g')
elseif h/g < 7
disp(h)
elseif g/h == 7
disp(g)
else
disp('h')
end

a) h
b) 28
c) 4
d) g
e) Error

17
Answers: Multiple Choice

1) What does the following code output in the Command Window?

x = 3;
y = 6;
if x == y
z = x;
elseif x ~= y
z = y+x;
end
disp(z)

So, we have assigned 3 to x and 6 to y. The first part of the if statement checks if
they are equal: they are not, so we will continue.

The next part of the statement is the else-if portion where the condition is “x is
NOT equal to y”. This is true, so we enter this statement. Within, we assign z to the
sum of x and y, so that would be 9.

At the end, we use disp(z). Since the z is not within apostrophes, that means we are
outputting the value of z and not the letter itself. Therefore, the output in the
Command Window is 9, i.e., answer choice d.

2) What does the operator = do?

a) Variable assignment is the correct answer


b) Boolean operator for equality
a. This is incorrect since two equal signs are needed to test for equality.
c) Not equal to
a. Also incorrect since we need a ~ sign.
d) Or
a. This is represented by two bars | |

18
3) There are four errors in the code below. What are they?

if pressure = 10
disp(pressure is high)
else
disp(pressure)

First, we are checking a condition involving the variable pressure. The first error is
that we never defined it.

Second, the if statement is checking if pressure is equal to 10. We would need 2


equal signs, since one equal sign is for variable assignment.

Third, the disp(pressure is high) does not make any sense since it is a sentence
and there are no apostrophes surrounding it. (Note, the disp(pressure) under the
else statement would be okay if pressure was defined originally. The spaces in
“pressure is high” make that input definitely not a variable, and therefore, the
apostrophes are needed).

Lastly, there is no end to finish off the statement.

4) What does the following code output in the Command Window?

g = 4;
h = 28;
if h/g > 7
disp('g')
elseif h/g < 7
disp(h)
elseif g/h == 7
disp(g)
else
disp('h')
end

Let’s go through line by line to understand what the output would be.

19
First, we assign 4 and 28 to g and h respectively.

The first if condition is asking if the h divided by g is greater than 7. If we do h/g


(28/4), we get exactly 7. So, this condition is NOT met.

The second asks if h/g is less than 7. We know that h/g is 7, so this condition is not
true as well.

The third is asking if g/h is equal to 7. Note that this is now g/h, NOT h/g. g/h is
4/28, which is 1/7. This condition is not true either.

The else statement contains every other possible case, so this is the code we will
run. It will be the letter h in the command window. So the answer choice is a.

20

You might also like