 Today, we will start discussing what is generally called the control structures in C plus plus. They encompass conditional execution of statements, something which we are going to see in some details today. The control structures in C plus plus also provide for building iterations or building constructs such that some instructions of your program can be repeatedly executed. Why would you like to do that is something that we have to see through some problems, but essentially it is the control structures which give the enormous power to us to write appropriate computer programs such that not only we can implement our computational logic properly, which may require conditional execution of statements, but we can also specify iterative instructions, which can mean thousands of instructions are executed while you write only four or five instructions or ten instructions, so that is the beauty of iterative solution. Today, we are going to discuss the problems that require conditional execution statement and to illustrate our point of flow of control, we will introduce a new graphical representation of our algorithms called flow charts. Subsequently, we will discuss the if, if else and switch statements. I will briefly describe the labs next week and the lectures next week and some general announcements at the end. So what are flow charts, first of all? They use a graphical notation to indicate how in what sequence the instructions in our program are executed. It might appear rather silly because when we consider programs such as the one which is written here on the screen, the flow of control is obvious. First instruction, the first instruction then you execute the second instruction, then the third, then the fourth, but graphically we might want to depict this in some kind of action boxes. The rectangular boxes that you see are called action boxes. Inside each action box, some activity is written which is expected to be executed by the corresponding instruction. In a flow chart, typically you write the actions in plain English. It is not necessary to write C plus plus statements. I am just illustrating the point. You will notice that the arrows very clearly indicate what will be done first, what will be done next. An arrow head says that the instruction C in greater greater b will not be executed before C in greater greater a is executed. Similarly, sum is equal to a plus b will be executed only after C in greater greater b is executed. If you look at the logic of this program, even if I interchange the first two boxes, will it affect the result? No, but if I put the third box at the top, then clearly I will have something very funny happen because sum equal to a plus b, if executed without inputting values of a and b, it will just collect some garbage that lies in the location for a and b, calculate the sum and give it to us. That is why even this simple sequence is important because sequences cannot always be interchanged in terms of the actions. This is the notation for a flow chart. There are a couple of other notations. For example, start of the algorithm is often depicted by writing start in a in a elliptical box. Similarly, end of the algorithm is depicted by writing stop at the end, but that is notional. Most of the time, if at all we draw algorithms, we will be drawing those flow charts for representing a segment of our logic. Notice that we need not write c plus plus statements. So, this flow chart indicates that I can just say input a, input b. Sum is equal to a plus b is a universal assignment operation that we understand now and we output this. Here is a simple computational problem. Starting from a point, a person starts walking at a fixed velocity. The steady speed is given as 2 kilometers per hour. He walks for an hour. So, write a program to determine the distance traveled by the person in some given time period. I can formulate a mathematical equation to represent the relationship between the distance traveled and the type. That would be a straight forward straight line relation and the straight line relation would depend of course, upon the time, but let us say this is one hour and this is one, two kilometers. So, the straight line will be, you agree? Now, obviously, if I want to determine what is the distance traveled by the person at any point in time, I will have to find out what is the value of d for a given t as per this formula. d is equal to 2 star. In fact, it is an absolutely straight forward problem. I would like to mention at this juncture that you may want to consider this to be a particular case of a more generalized mathematical model, which is y is equal to m x plus c. You are familiar with this. Represents the equation of a straight line. Now, if this was my algorithm, this was my problem, how would I write the program? Well, this is a sample program. Forget the first three, four lines, do not waste your time looking at that, but it asks you to give a value of time. Notice that I have written back slash n in the C out statement indicating a new line character. That is one way of writing it. The other way is to introduce a very special name called n l as a separate item to be out. More importantly, I get the value of time as input. I calculate distance equal to 2.0 into time and I output distance traveled is this. Any problems with this algorithm? No issues. Come again, slash n. His question is what is the function of this slash n? You will recall that when we discussed the care type, we said a care type is capable of storing the ASCII code of a symbol. Now, there are symbols which are obvious and visible to us like a, b, p plus minus and those we can write in our programs as they are, but there are symbols which are not visible to us like a space. How do you write? Space is actually visible when we edit a program because a blank space appears, but a tab which is like 8 spaces or 6 spaces, it will not appear explicitly as a tab. Similarly, on the screen when you see, you start writing a program like this and when you press carriage return or enter, you go to the next slide. Now, there is a character there which is called the new line character that is not visible to you, but when you press enter in your program editing, that new line you automatically get. Now, we are talking about producing an output where things should appear on different lines. How do you ensure that? How do you tell the C plus plus to produce an output after that printing this line? Let us say you after printing this message, you want the machine to say next thing should go to the next line. How do you say that? So, you have to insert a new line character forcibly into the output stream. That backslash n is nothing but that new line character. So, is this clear? Yeah. The errors would be for completely different reasons. New line is your op-rees understand. New line is an option. If I do not give the new line, it will not produce a new line in the output. So, subsequent output will come on the same line. This is not an erroneous statement. So, if you got an error, go back to your lab and find out what other errors are. If I were to write a flow chart for this, how would it look like? It would actually be very simple. I will say input t, then I will say d is equal to 2t and I will say, notice that I am not using the names which I have used in the C plus plus flow. I am also not using the rigorous C plus plus please syntax of writing an expression. I am writing in commonly known mathematical terms and I am using symbolisms which should be obvious to anyone who has read that problem. Is that correct? So, the relationship between a flow chart and a program is more logical. It is not 1 to 1. You do not have to write exactly. The point being made here is, this is a straight forward problem. You write a sequence of instructions. They are executed in the given sequence. Press tau. You get the final answer. And now, complicate the problem slightly. Read this problem. The first part of the problem is same. It says person walks at a steady speed of 2 kilometers per hour for one hour and the person then starts running at a speed of 4 kilometers per hour. And that he does it for 2 hours and then stops. Write a program to determine the distance traveled by the person in some given time p. Problem is same. But now, if I were to mathematically formulate the relationship between distance and time, I actually get two straight lines. The first straight line, let me write down slightly elongated scale on the time side. So, this is 1 hour, 2 hours and 3 hours. Let me write down a slightly compressed scale on the y side because physically the screen is limited on the vertical axis. So, let me say this is 1 kilometer, 2 kilometers, 3 kilometers, 4 kilometers, 5, 6, 7, 8, 9 approximately. So, this is 8 and so on. So, what will be the graph that will be depicting the relationship between distance and time? For the first hour, the person walks at a speed of 2 kilometers per hour. So, that means in the first hour, the fellow is likely to reach somewhere here. So, the straight line depicting his movement will be like this. But after that hour, the person starts running at the speed of 4 kilometers per hour. In 2 hours, how many kilometers the fellow will run? 8. He has already traveled 2 kilometers. So, the next straight line will be from 2 kilometers at this point to 10 kilometers at the end of 3 hours. So, I will require one more point here somewhere and let us say this is that point. Oops, sorry, I cannot delete this. So, I will leave it as it is. But effectively now, it is not showing 2 different straight lines. Let me see if I can delete, unless I ok fine. I will just leave it at that. But you agree that there are 2 different straight lines. Let me draw these straight lines something like this so that they are sharply known. The point is given a value of time. Time anybody can give. Time can be 1.3 hours, 2.4 hours, 0.6 hours. By the way, we should also discuss how exactly one would give time. Usually people when they tell us a time value, they tell it in time, hours, minutes and seconds. Have you anybody seen time is 2.63 hours after that point? No. So, that is another point that we will have to worry about. But currently we are talking about maths. But maths also given a time, there is no single formula which will calculate the distance. In this part of the curve, what is the equivalent of distance is equal to 2 times time. But in this part of the curve, what is the formula? Is that correct? No. D is equal to 40, is it correct? Plus 2. He is suggesting D is equal to 40. Let us calculate. Let us say D is equal to 2 hours. As per this formula, I will get the answer as 8 kilometers. This is clearly wrong. The formula suggested is D is equal to 40 minus 2. Let us apply that. At 2 hours, this should be equal to 8 minus 2, which is equal to 6. Is that correct? At 3 hours, what will be the result? 12 minus 2, which is equal to 10. Looks correct? Some verification that we should do. The main point is not that. The main point is how do I write my program? If I write D equal to 2T, I will get correct answer if T is less than 1 hour. If I write D is equal to 4T minus 2, I will get correct answer only if T is more than that time. But not otherwise. We cannot write a correct C plus plus program with the given power of calculation that we know. We need something more. And that something is provided by a construct, which we shall see in the context of another problem, which is very similar. Cost of a ticket for a bus journey from some point A to some town B, whatever, is let us say 25 rupees, 50 percent. But the bus company gives a concession for children. If the age is less than 12 years, the cost of the ticket is only 12 rupees 75 percent. Given the age of the passenger, write a program to calculate the cost of a ticket. We realize that this is very similar in concept to the problem that we faced earlier. That if age is up to 12 years, the price of the ticket is something. If the age is beyond 12 years, the price of the ticket is something. No computation is involved. We have to finally look at the statements that are written here on the slide. Int age float ticket cost. Is age integer? I have declared int age. I have declared float ticket underscore cost. Obviously ticket underscore cost is fraction. I have rupees and price. But is age integer? Yes and no. What is the right answer? The actual answer is age of a person is not integer unless you measure it in microseconds. If you measure the age in years, which is what we normally do, the age of a child could be 10 and half years. My age is for example, 63 and half years. I would not say 63. However, those who say yes to int are also right because in the context of the problem that we are solving, it is immaterial what exactly the age of a person is in terms of fraction. The problem simply states 12 year or more, 12 years or less. In which case anybody who says 10, 11, 9 is a child, anybody who says 13, 14, 15 is an elder, anybody who says 12 has a problem. Generally the parents will always say 11 when the person has birth date today or yesterday. But if the birth date has happened yesterday, today the age will be 12 anyway. That is more for the legality and morality. But we agree that as far as this problem is concerned, integer age is perfectly fine. Anyway, so I define these and I input the age. So I got a value of a, 53, 12, 10, whatever. Now I have a problem. How do I write instructions to calculate the correct cost? In this case, we wish to tell C plus plus a very peculiar thing because remember in that program somewhere we will have to say cost of ticket or ticket cost is 12.75 and somewhere we will have to say cost is 25.5 because both of them will be valid in some time or the other. But what we want to specify is that depending on the age you execute that statement or that statement. So what we want to say is if age is less than 25 years then calculate the cost of ticket as 12.75 else calculate the cost of ticket as 25.5. So what we wish to do is we wish to write a program which will either execute the first statement or execute the second statement but never both. Currently we do not know the mechanism. Whatever we write is executed as and that is why we say that this is an extremely powerful construct which is provided in C plus plus to an if statement. So what we want to do logically is we want first to examine the value of age. If age is less than 12 we want to do something. If age is not less than 12 we want to do something else. In the flow chart this is depicted by a diamond box. Remember we saw all rectangular boxes. Rectangular boxes in a flow chart always show an action but a diamond box shows a question to be asked, a condition to be evaluated. For example I may say here age less than 25. So this is not a statement. This is a question. Is age less than 25? The answer is either yes which is logically called true or the answer is no which is logically called false. Some of you would be familiar with true and false nomenclature in the context of Boolean algebra if you have studied it. It is same as true and false. The point is now I have two different paths. Only one of the two will be taken not both, never both. Obviously if I have instructions to be executed if age is indeed less than 25 I would write them beneath this arrow. If I have instructions to be executed if the age is not less than 25 I should write them beneath this arrow. Eventually whatever instructions I execute in either this path or that path the arrows may come back to indicate subsequent flow of instructions in the normal sense. The flow chart depicting the solution for this problem is shown here. For the benefit of people who want to write a C++ program directly I have written C++ instructions syntax inside the boxes although as you know it is not required. So I take input as age. I ask the question is age less than 12? It is this question which is not written exactly as per the syntax of C++. We shall see what the syntax is. But the answer is true or false. If the answer is true Tc which I have used as a short form to represent picket cars is set to 12.75 and then I go down to output. On the other hand if age is not less than 12 I go to another path completely. Execute another instruction Tc equal to 25.50 and come back again to do this. Now this going somewhere and coming back, going somewhere else and coming back has to be indicated in a text form because our program is lines of text. So how do you when C++ compiler is reading our instructions how from a text file or lines of text can it understand that these lines represent actions in the yes path those lines represent actions in the no path and after that this whole Jamela is complete. Subsequent things are to be executed in any case. How do we say that? That is where the powerful syntax rules of C++ permit us to do that. The instruction which implements such conditional execution is called the if instruction. The if statement is written in the form that is shown there. If in parenthesis condition parenthesis is closed statement one semicolon else statement two. So the composite if statement consists of these two lines or these two instructions if you may so far if and else it is a pair. If some condition is true execute statement one otherwise execute statement two. What are conditions? Conditions are like the question that we ask usually there will be comparison conditions because we are doing with values. So I have given some examples of the conditions that can be written count less than equal to n that is a condition depending upon whatever is the value of count and whatever is the value of n at that instance this condition will be either true or false. By the way when we write the program we do not know in advance whether the condition is true or false. If we did we would not write any statement. Values may change when the program is executed today the program is executed with one set of values some conditions may be true some may be false tomorrow the program is executed with some other values the same conditions may work out to be false some other conditions may work out. I have written a slightly complex example new underscore value minus old underscore value less than one point zero e minus five. Please note that condition is a comparison of values there is a comparison operator such as less than less than equal to we shall see what those operators are and on either side of those operators are values and each value can be written as a full-fledged expression. So this is not to be confused with an assignment statement I am comparing two expression values in general more specifically I may be comparing simple things like count less than equal to but comparison such as these are perfectly valid look at the third line of the examples age greater than equal to twelve the other condition written is age less than twelve do they mean the same thing do they mean something different yes they actually indicate the same concern that we have all computation but they are written as a negation of the other. So consequently if I were to write that diamond box or if the if statement of this if age greater than twelve is the condition I write then against the statement one I have to write what I have to do if age is greater than and against else I have to write the other one on the other end if I say if age less than twelve then statement one will indicate what is to be done with ages less than twelve and else will indicate what is to be done is that it is pretty simple stuff actually but it is critical to understand the exact syntax in the mean. So the last few lines in the slide give exactly how C plus plus will approach it first it will evaluate the condition it will please note now the rules are as rigorous as the assignment statements we have spent a lot of time in understanding why I want write a square equal to five because a square is not a valid left hand side similarly we have understood that if we say m is equal to m plus five there is no confusion or dichotomy it then look at the left hand side first it looks at the right hand side evaluates expression gets a value puts it in the left in exactly the same way we should understand the rules of the game for the if statement if something statement one semicolon else statement two semicolon is a group in this entire group C plus plus first looks at the condition then bother with anything else it evaluates the condition it evaluates the condition to a logical value which is true or false if the value is true it will execute statement one if the value is false it will execute statement is that clear the general flow chart for any statement will be the most important point to remember apart from the logic of if is that in either case after executing statement one or after executing statement two the control will go within the C plus first program to the statement written immediately after the L state that statement will be executed always no matter what was the condition is that clear so here is an implementation of C plus plus of our problem if in bracket age less than 12 bracket close ticket cost is equal to 12.75 semicolon else ticket cost is equal to 25.50 semicolon you get this very simple please understand that this entire segment is to be considered as some kind of a block it's a single statement in a sense it's compound but the single state if something else it is also possible that we may have a situation where we want to conditionally execute some statement if the condition is true but otherwise we don't have anything special to do we want to carry on for such a block would be represented by I'll say condition C so you see on the else path there is nothing to be done in such a situation I can simply write if C and carry on there is no else path is that clear why would I do such a thing can I use this structure to solve the bus ticket problem you can I will just write down some simple instructions just check whether they make sense we agree that these two lines will actually solve my problem correctly what I am doing is clever first time seeing look I don't even care for your age I will assign the value of ticket cost as 25 25.5 now I will say what is your age oh resident 12 sorry I get back my 25.0 TC is equal to 12 points this is a neater code in some sense and there are some problems where we will find that it is precisely use of such tricks which will help us enormously shorten our program however please note that in half the cases on an average this program will execute an assignment operation twice in fact every time a child comes for a ticket purchase I will first make an assignment statement of 25 and then check every time an elder person comes I will not evaluate any condition first I will assign the correct value examine the condition condition is false so the other assignment will not is this small squiggle but it is valid and this is a version of the statement which is permanent what if I have multiple actions to be executed on either side of true or false for example let me call these as s1 s2 s3 and let me call this as let's say yes and no so I will call this n1 there are some statements why is equal to something something is really equal to something I really want in my in my complicated logic I have in my life to solve a problem it says if some condition is met then do this do this do this do this otherwise do that do that in either case go back as here is where we use the power of the notion of a block where c++ recognizes anything which is enclosed in curly brackets as a single statement it is therefore possible for us to write if c a curly bracket s1 s2 s3 curly bracket closed else another curly bracket n1 n2 which semicolons and then a curly bracket what c++ says is a you are saying if c then a curly bracket that means now till the end of the this corresponding curly bracket there may be 510 500 statements all of them are to be considered to lie on the true path of the country and I'll execute all of them if ever I come here however if the condition is false I will never come to this curly bracket I will go to else statement else again has a curly bracket and therefore I will execute all those things n1 n2 or whatever you have on the no power and till I complete the end of that curly bracket however in either case I will go to the next statement which follows this is this clear so this is the power of the logic of treating multiple statements as a single statement and since in most problems we would not know whether an if statement will have after the condition only one statement to be executed or more on the else side only one statement to be executed or more even when we write the program it may require only one statement but in future when I modify the program I may have to include additional actions on the true path or false path and therefore a good practice not mandatory but good practice is to write a program like this so forget the top few lines I get the age of the passenger check if age less than 12 opening curly bracket ticket cost is equal to 12.75 semicolon else opening curly bracket integer under a ticket underscore cost is equal to 25.50 curly bracket you see now the advantage I can put as many instructions as I want after this in my curly bracket they will all be regarded as a single in general a single instruction written in a line separately does not make sense to have two curly brackets around it so that is why we often will write this as this is the condition I will write a curly bracket here I will write statements here and then I will write a curly bracket this is a better practice after conditions you write a curly bracket in fact you go to the next line and first type the closing curly bracket now you go one line up and start inserting your notice the indentation remember I said you leave a few blanks at the beginning of a line to indicate what component of the program that code line belongs and here you can see the advantage whatever is to be done on the true side is indented two spaces on the right whatever is to be done on the false side is indented two spaces in the right so that way you can very easily identify the true block and the false one is that clear very good in fact this statement should be put inside the curly bracket this is a mistake you see the curly bracket merely enclosed statements ok curly bracket itself is not a statement so he is very correct thanks for pointing this out this should be semicolon curly bracket semicolon so you got you got the idea now if I have multiple statements I could enclose them in curly brackets and they would be treated as a single state here is another variation we are luckily I have collected that error this variation checks if edge is greater than equal to 12 remember I said the two conditions are equivalent but one is negation of the other so now you will see that what was appearing in the true part of the previous if statement is now appearing in the false part of this is under the else ok so if edge is greater than 12 ticket cost is so much else ticket cost is so simple isn't it conditional execution you can extend it to include any kind of complications what kind of complications may result now the bus company introduces senior citizen construction people like me who are older than 60 years can pay only 20 rupees not as less as a child but not as much as a working adult how do you take care of this situation now there are actually three different conditions one condition if you are older than 60 years another condition if you are older than 12 years but less than 60 years third condition you are less than 12 right one possible program is written here if edge is greater than 60 ticket cost is 20 else if edge is greater than equal to 12 ticket cost is equal to this else ticket cost since the conditions here are such that one flows from the other next flows from this and therefore this structure is called an if else ladder you know the ladder CD climb up so there are steps in the CD so these are like steps first step this then this then this then so this is a very simple structure you can have more complication if you remember that after if and after condition you are permitted to write a statement it doesn't say which statement the statement itself can be an if statement as you can see it is here within that if statement on the s side and l side again there can be other if statement you can complicate the life as completely as you want one of the problems in the handout that I will give you ask you to implement that complicated so you will have this is called nested ifs if within an if and then you may sometimes have a problem that the else statement that you will write somewhere deep you may forget this else correspond to this if or that if or that so that is where the indentation will help you please note indentation is only to improve your readability c++ doesn't give a damn whether you indent or not but it will correctly keep track of how many ifs you have got how many else as you have got and which one matches yeah no no no please note if age is greater than 60 ticket cost is 20 will be executed but the next statement is not written as if it should be always executed there is an else there else else means that only if age is not greater than 60 then whatever is stated here will be executed it will be the control will never come to that statement if age is greater than 60 that is the whole point okay just let us this is a good question that he raises so therefore you should always look at the flowchart of this the flowchart of this structure says is age greater than 60 if the answer is yes you will come here and do what Tc is equal to 20 only if the answer is no you will come here on the no side when will you come the else statement the else statement is executed only if the answer is no to the first question otherwise even after coming to the else side you are not doing anything concrete you are again examining another condition so there is another which says is age greater than equal to 12 here the answer could be yes or no if the answer is yes what are you saying Tc is equal to 25.5 if it is no you are saying Tc is equal to 12.75 and in here you are coming in either case like this and here you are coming in either case like this this is the logic which is implemented by this yeah you can okay his question is can I not write this differently by saying if age is greater than equal to 12 and age is less than something as a composite condition we shall see those composite conditions shortly but to answer his point where he is asking his question was can I not write it differently of course you can write it differently and of course there is no unique way of implementing a conditional logic in your book no unique way when you see more complicated problem that one of the problems in the problem said I will not be surprised if there are 20 different ways in which you write the conditions in C++ each one of those ways may be correct that's perfectly fine but let's come back to the question that our friend had asked are you are you convinced now what is happening sorry I forgot to ask this question you see I am not coming to examine whether age is greater than equal to 12 or not I am not coming to that point at all if age is greater than 60 if age is greater than 60 I am supposed to calculate Tc equal to this and get out I will come to this part only if that condition that is the power of else if I forget to write else what you say will be