Tip:
Highlight text to annotate it
X
In this lesson we are going to take a look at the decision branching statement, the if-else statement
Now the if-else or decision branching gives us the ability to change the direction of the flow of control of the program, of the algorithm.
Let's take a little review. So far what we've seen is that we have input and we have output,
and we can remember information and we can modify information.
The other two really big capabilities that we need to be able to compute anything are
decision branching and looping, that is to repeat something.
So let's take a look at our if-else statement. The syntax is as follows: if expression closed in parentheses statement one else statement two.
Now in the coming lectures I'm going to give the syntax of different constructs in the same general format.
and what I'm going to say about expressions and statements and key words is going to hold through the other lessons.
So, let me go through this. The key words, or reseved words here are if and else. Remember all reserved words are always lowercase.
The expression here must be contained within parentheses, even if you are to negate that logically.
For instance, if you wanted to say well if not this, then you have to put parentheses around that.
So what is expression? It's a valid C++ expression that evaluates to true or false or a numerical value.
Again, remember zero is synonomous with false and anything but zero is true.
And what are statements?
Statement one and statement two, they are individually either a single simple C++ statement with the required semicolon,
or they are a compound statement.
So what is a compound statement? Well rather than just a single statement, you might want to execute several statements.
So you create a compound statement by opening a set of curly braces and having multiple statements.
Notice that I've indented and in fact you see statement one and statement two are indented under the if and else clauses
You want to do that to format your code to show how things are flowing.
So how does this thing work? Well it's very simple of course.
If expression comes out to be true, then statement one is going to be executed and the else is ignored,
and then control passes down anything down here whatever statements followed the if else.
If on the other hand, expression is false, then statement two is executed and statement one is ignored.
it's really pretty simple
Okay, I want to give you a warning to begin with.
This semicolon right here. If you put a semicolon there, what happens is that terminates or ends the if statement.
The compiler sees if, then some expression, then an empty or non statement.
It will execute this non statement which means do nothing and then it's done.
Okay, so this cout "It's hot outside," in this case will always be executed.
The curly braces here are completely superfluous and the indentation is misleading it would be the next logical statement after that if.
Now there is something I failed to say, that might make this clearer. The else is optional.
You do not have to have an else statement, you can have just an if. So that's what the case is here.
Okay, example one
if four, cout "hello." How is this going to be executed?
Well four is an expression. It evaluates to either true or false or a number. In this case a number that's non zero. If it's non zero, then it's true.
Okay, so if true, then cout hello. Which means what? cout statement is going to get executed because that's true. It's always true.
So this is actually kind of a foolish a statement because four is never gonna change, there is no real decision to make.
I might as well have just said cout hello.
On the other hand, if I say if zero cout hello, well zero is what? That's synonymous with false and this cout statement will never get executed.
Let's go onto a realistic example.
Let's suppose that we prompt for the radius of a circle. We're going to read the value into a variable called radius.
What we're going to do is calculate the area of a circle with that radius. Well I want to weed out bad input.
So suppose that somebody enters zero or negative six or something like that. We don't want to calculate an aera.
One of the things that we can do is this. We say if radius is less or equal to zero, then we have a compound statement.
We're going to output an error: no circle has non-positive radius.
Then I'm going to execute the exit function. Now you don't know what functions are at this point except for main,
but suffice it to say at this point that the execution of this statement will terminate the run of the program.
It does it gracefully, and I'll explain this in a slide later on,
but it just jumps out of the program terminates everything the rest of the program is not executed
On the other hand, if radius is positive, if somebody enters four, then all of this stuff here is not executed.
Control passes down to the statement where it calculates the area, which is assigned PI times radius times radius.
Notice that the pie is all upper case so it's taken for granted that that's been declared as a constant and given the value 3.14159
Then we cout the information and we cout exit. Now is this a good program? Well, it's not really.
You certainly want to give somebody another chance to enter a more reasonable radius. and we'll be able to do that eventually.
Still even if they do give you an erroneous value, you'd certainly like to at least finish the program and to output the goodbye message here.
So let's revisit this. Let's look at a different version of this piece of code.
Again, we're going to prompt for and read in the radius, but now our conditions are going to be a little bit different.
If the radius is less or equal to zero, I am simply going to output in error message, and then I skip the else. So all of this code here is skipped.
and I come down to the output statement ending this example and I can gracefully end the program with return zero.
On the other hand, if a radius value that is positive is entered, then this is false.
The condition that the radius is less than or equal to zero is false.
So this is not executed, and control passes down to the else
where I have a compound statement where i'm going to calcuate the area and then I'm going to output it.
Then control passes out of the if-else and hits the cout statement.
I want to say something about the use of tabs.
Tabs are a real problem. You really should avoid using the tab character when you are editing your files.
When you indent and you want to indent when the control of the program enters a new scope, so to speak
Indent two spaces and be consistent. Not one, not three, not four, and five is right out. Don't tab, use two spaces.
The reason is that in some editors a tab character can be two spaces or five spaces another editor it'll be one space or three spaces.
So the format comes out really ugly. Besides the fact that when we print assignments it can get really distorted also.
So you want to be consistent with your spacing and you're formatting.
If you look at this block of code, it's just horrible to try to follow what's going on. If you consider that to be the line of executions so to speak.
I can't quite tell what's going on here. The closing curly brace of course shouldn't be there it should be over here.
Incidentally I might point out that you'll see some authors start their curly braces over here instead of here.
Please do not do that. That's a standard that we do not live by.
Let's take a look of another example. This is what I call an E-siv so to speak.
I'm going to create a sequence of constants. I've got three of them here and I didn't include the rest just because of space.
What I'm going to do is create a block of code that I can drop an average into and have it assigned a grade.
So I'm going to have a constant for max A, min B, average, min C etc. I'm going to prompt for the average and read it into a variable called ave.
I'm then going to jump into an if-else statement.
Now, the expression for the if, that is the condition, is to start with if ave is greater than MAX_A greater than 100,
Then I'll put an error message. Control then would pass out to the end down here. It would skip everything under the else.
If that's not the case, if that's false, then it falls into the else, and I hit this next if statement right here
So what do I know so far? At this point I know that the ave is what? It's less than or equal to 100.
So I'm going to ask the question is it greater than or equal to MIN_A? If it is it's greater than or equal to 90.
That means I'm going to assign the grade of A to grade.
If it's not then have has to be less than 90.
So I'm going to ask the question is a bigger than or equal to MIN_B, which is 80. If so, then I'm going to assign a B.
If not, then ave has to be what? Well if it's not greater than or equal to MIN_B which is 80, it has to be les than 80.
So then I'll ask the question is a greater than or equal to MIN_C? If so, then I'll assign C to the grade.
And, since I've gotten tired of this, I'm just going to give everybody else F.
The problem with this structure, this is perfectly good programming, but the difficulty is that because of the indentation,
everything is kind of migrating right and you end up losing space.
A perfectly acceptable way to rewrite this is as follows.
I'm going to write it as if ave greater than MAX_A do that else if, else if, else if, else if, else if, else, etc.
Now want to make sure you understand something else here.
You have if some expression and a statemtent else, and another statement.
A common mistake made by people first learning programming is they'll try to put some sort of expression here, say not expressoin.
but this is totally unnecessary. If you think about this, this is if expression and then I'm going to do this, otherwise I'm going to do that.
I don't need to say anything here and in fact it won't compile. So, don't make that mistake.
Okay, let me explain the exit functin verses return 0;
In both cases, when these expressions are evaluated you're sending a value, an integer, back to the operating system.
Those values can be used in the future, we will not use them in this course, but can be used to signal different situations.
When zero goes back to the operating system that can be interpreted as the program ran to completion.
It hit the very last statement return 0;
That says everything went fine in the program, When you hit an exit, you send a numeric value, say three, back to the operating system.
What that means is that some sort of an error occurred, like the one a minute ago,
and the value can be mapped two the error conditions and some action be taken.
When an exit function is executed all variables are deallocated everything a set down gracefully,
but the program is not completed. It does not run to completion.
So the exit function is only used under the conditions that something bad has happened.
I introduce it here now now because we don't have the standard way of handling exceptions, handling difficulties in a program.
That's called exception handling it's a rather advanced topic and of course we can go over it here now.
So, end your main program with a return zero use the exit only when it's an indication of some failed state in a program.
That's the end of the session.