 So all of you have seen the videos for this lecture. This was the sample on how you have to take the answers. It won't take long. The first set of quizzes are only recapped quizzes. Then we will start with the practice problems. So here is the first quiz. Why do we need iteration or looping constructs? Why not simply repeat code as many times as we need? There are several reasons which are mentioned here. Take one or more of those which apply. Alright, let's have a sample answer from someone here. Possible source of errors. What about B? Sometimes the number of iterations are not known. So how many times will you repeat the code? Three times, five times, ten times? If you have to do something n times where n itself is dependent upon an input value, you cannot predict while writing the program and how many times you have to repeat the code? You just can't do that. You will have to use an iterative structure. What about C? That is also true. If you repeat the code physically right again and again, you are actually wasting your time, wasting program space and wasting the fact that the code once written can actually be reused. So if you just repeat the blocks, you cannot reuse the code. In short, all three are valid. For all these reasons, we must have repetitive structures, repetitive constructs. Code cannot be reused if you repeat the code. It is not being reused. We would like to reuse the code. Look at this code. This will add two numbers that I input. The point is it is very obvious that I will have to, suppose I want to add five numbers, I will have to repeat this code five times. That means the code which I have written, I cannot reuse, although I have written it. So look at all the questions that were asked there. First, there might be an error if I write too many lines. I might make some error somewhere. Second, I am not able to reuse this code. Third, if I do not know how many numbers I want to add, how will I write a program like this without an iterative structure? Suppose I want to add n numbers. That means I must read only n values. Then n may be five today, ten tomorrow, eleven for someone else the same day. How your program will work in that case? That is the reason why you need iterative structures. Is that clear now? The next question. In which of the following looping constructs in C++, the loop must iterate at least once. So you have a do-by-loop, you have a by-loop, you have a for-loop. So in which of the following looping constructs, the loop must iterate at least once. If you think that a loop must not iterate at least once in any one of these three, the choice is none. So think about it. If you have seen the video, you should be able to answer this question very easily. In fact, no logical thinking is actually required. When the constructs were explained, this was very specifically mentioned. So have you all solved it? Anybody who is still writing? Everybody has done it. All right. What is the answer? Do-by. So do-by-loop will execute the loop body at least once, and why? Because the condition of exit or continuation is checked only at the end of the loop after the body is executed at least once. Whereas in other cases, the exit condition is checked at the beginning of the loop. In a simple conversion of a do-by-loop to a by-loop, which of the following are true? More than one might be true. A, the loop body must be replicated twice if I simply want to convert do-by-loop to a by-loop. B, the loop condition must be replicated twice. C, both A and B and D, either A or B, but not both. So you have to picture a do-by-loop. Then you have to assume that you are rewriting that do-by-loop as a by-loop. So if you want to implement exactly the same logic that was implemented by the do-by-loop, which one of these things you may need to do? So have you written your answers? Not yet. Raise your hands if you are still thinking. Several. All right. Think. These are only recap quizzes. Actually, if you have seen the lectures, you should be able to answer them off your head. What it means, perhaps, is you need to watch those lectures more attentively. Please note that those have been deliberately made into very short videos so that you don't get bored while listening to them. I might like to add that it may be useful to keep a notebook with you when you are watching videos and just jot down some notes as if you are attending a class because that is the habit that most of you follow. So it might be useful to do that. They are not movies, you know, for entertainment. This is serious business. All right. So everybody finished? I will not discuss the answer because I just realized that I am going to collect these slips and people may change their answers. So we will discuss this later. All right. So this is another quiz. We have a for-loop here. In this for-loop, there is an assignment x, there is a condition y, and there is an assignment z. This is followed by the loop body w. So x, y, z, w. So there is an assignment, there is a condition, there is an assignment. These are the three parts of the for-statement and there is a loop body w. What is being asked is in what sequence of execution will these things occur? So for example, choice says first assignment x will be done, then condition y will be checked, then assignment z will be done, and then w will be done, and then things will be repeated. This one says x will be followed by y, condition checked, then w will be done, then z will be done. Third one says x will be followed by z, then y will be done, then w will be done, and so on. So which one of these four is the correct logical sequence in which things will happen? If you can picturize in your mind the flowchart for the for-loop, you should be able to answer this very easily. No discussion on this part. It's just a recap quiz. Each one of you is supposed to recapitulate what you have seen and answer these things. Everybody done? So for those of you who are having a difficulty, I think my suggestion of keeping a notebook with you when you are watching these short videos will be extremely helpful so that you can actually jot down some important points about whatever you have seen. It is the fifth question. Consider this loop. For x equal to y, x greater than equal to 10, x is equal to x plus 1. The loop body is simply y is equal to y minus 2. Now suppose we start executing this loop with the value of x as 10 and value of y as 10. So initially x and y both are 10. How many times is x equal to y executed and how many times y equal to y minus 2 is executed? So these are the possible answers. A says only once each. B says x equal to y will be executed once but y equal to y minus 2 will be executed infinitely. That is, it's an infinite loop. C says both these will be executed infinitely. And D says x equal to y will be executed once and y equal to y minus 2 will be executed zero times. This actually requires you to apply the logic of the for loop. What exactly will be the execution pattern? So recall that, solve the problem on your notebook and then write the answer. We will be formalizing these recap quizzes into marked answers. So today is some sort of a practice for you but from tomorrow onwards when we collect those things we'll actually be entering them onto a spreadsheet and we'll be considering them as part of the evaluation. All right. All papers collected will now move over to the practice problems for these lectures. So this is a simple problem which all of you would be familiar with. So this is a practice problem now you have to actually solve it. We want to compute the factorial of a non-negative integer using a looping construct. There are different ways in which such a thing can be implemented. You basically read a number n whatever, maybe 5, 4, 3, 8, whatever. And factorial means you have to calculate the product of 1 into 2 into 3 into 4 into 5 up to n and whatever is the final factorial value you have to print it. So relatively simple program, here is a code that has been pre-written with some question marks. Int n, int i, then there is some question mark, question mark, question mark, factorial n equal to 1. Factorial n is obviously a variable name. So what is missing is the type, what should be the type of factorial. The next statement says given it reads the value of n then there is a for loop, for i equal to something that is the question mark. i less than n, i equal to i plus 1. The body of the loop is factorial n equal to another set of question marks. And output is factorial of n is factorial. So n is given as input, factorial n is calculated and printed as output. You have to ensure that whatever you write in place of those question marks should make the program a valid program and a correct program which brings the correct value of factorial n. So now start thinking and start writing down what you think should be the replacement for question mark. First you have to attempt, each one of you have to attempt this individually. So write down on your notebook what should be the answer. It is a simple problem so it should not take more than 2 minutes. People are writing programs to calculate factorial. I know that every one of you can write the program. The point is the program has been given to you. There are some missing aspects of that program. What you have to find out is what should you be writing instead of those question marks such that the program produces correct and good results. So as everybody written what should be there for the question mark? So please note again you don't have to write your own program to find out the factorial. Somebody, a friend of yours has written this program and has forgotten to write some points there or is confused. You have to help your friend. There are basically three questions to be very precise. What should be the type of factorial n? That is the first set of rare question marks. Here what should be the type? The next question is what should be the initial value of i for the for loop? And the last question is what should be assigned to factorial n? What should be the expression here? Three simple questions such that you should get the factorial value. All right. Finish now. At this juncture each one of you has to solve the problem oneself. So everybody done? Anybody not yet done? Please raise your hands. Ah, everyone done. As we normally do exchange your notebook with your neighbor. All right. How many people disagreed with their neighbors? Please raise your hands. Which pairs had disagreement? Now after the discussion how many of you still believe that your neighbors answer is wrong and your answer is correct? There is an agreement? All right. Let us quickly analyze. Here is an answer by Mudit. He believes that n should be declared as int. The program is wrongly reproduced. i was declared separately as int. So Mudit has written int n comma i. Even if he wanted to declare n as int, he should have put int n comma int i. Second, the word used for factorial he has used long. Do you all agree? No, some people don't agree. He has used initial value as i equal to 1 and he has used factorial n star equal to i plus 1. That means he is multiplying the old value of factorial by i plus 1. Do you think this will be correct? Those who say no, tell me why? i should be equal to 0, not 1. Why? Sorry. What will be the value of n? If it is 0, will the iteration execute even once? Because the condition says i less than n. If i is 1 and n is given as 0, i will not be, is that clear? So this appears to be right. Here is another solution by Piyush. He believes that factorial n should be int. First of all, he has invented his own name, fact n, whereas the name given in the program was factorial capital n. This might appear to be a very small deviation, but it could be disastrous when you have a long program written by Samma and you are adding a few statements where you make a mistake in using a name that someone has already used to define something. So you have to be very precise whenever you write a problem. Alright. Piyush also starts with i equal to 1, but calculates factorial n as factorial n into i. Is this correct? What is the mistake? He must, if he starts with i equal to 1, he must multiply this by i plus 1. What about int factorial n? Is that okay? Technically it is correct, but it will not be able to find factorial for very large numbers because int has a very limited capacity. So long is perhaps better. So here is a solution by Kshitij. He says it should be float. He correctly finds out that factorial n should be multiplied by i plus 1, but he uses float. And someone says double. Now suppose we use float, you will of course get a much larger magnitude, but will you not lose out on precision? In fact, will you not lose out on precision, even as compared to normal int? Now it depends upon why you are calculating the factorial. If you want its exact value, it is better to say that my program will compute exact values only for a value of n up to this. Beyond that, it will not compute. But whatever I compute is exact, which means you have to use some form of int only. Float will give you larger magnitude, but less precision. Is that clear? This you have to keep in mind when you solve the problem. Let's go to the next problem. I want to write a program to calculate the nth power of an integer where n is greater than or equal to 0. The integer m is given and you have to write a looping program to calculate m raised to n. There is a simple problem, the power function. How will you write this program? You can write it simply by multiplying m with itself as many times as is required to get m raised to n. All of you can write this program. Try to quickly write one on your notebook for two minutes. Just write a program. I will show you the code which has been already written later. But first, each one of you should write a program. You don't have to write in hash, include, etc., etc. Just write a program. Assume int m int n, for example. Read the values of m and n and write a program which will calculate m raised to power n. The logic is simple. Keep multiplying a running product by m n times. You will get m raised to power n. See, that's the problem. You all expect multiple choice answers. You don't have to write anything. That's not fair. In programming, you have to write programs. It's not a very long program. It's a short program. You should be able to write it quickly. The logic is very simple. Read the values of n and m. Set up a running product with some initial value. Say p is equal to something. Set up an iteration which will run n times and multiply p by m as many times as you need to find out n raised to m. Done now? I am doing this deliberately to tell you the importance of synthesis as opposed to analysis. Analysis means you look at something that is presented and find out if that is correct or not. Synthesis means you have to construct something yourself. And in programming, eventually, you'll have to construct programs. Whatever we are doing is merely for understanding things, but eventually you have to write programs. The point is if you have solved this program on your own, you may be much easily find out the missing part of the code which will follow. So those of you who have attempted to write the program, there may be mistakes that you might have made. Ordinarily, when you run your programs on the machine, the machine will tell you if there are any errors. But here is a chance to look at a pre-written program. So this logic may be different than what you had in mind. We'll continue the discussion later, but we'll stop the discussion now. Now every one of you, I request you to look at this answer that has been given. It's a skeleton of a program. In this skeleton, some pieces of code are missing. Let us read this program. M, N, and I are declared as integer variables. The result is declared as unsigned long. By the way, reflect on the previous question. The samples that I showed, somebody had said in, somebody had said long in, somebody had said floor. But nobody had thought of unsigned long. Go back to the previous question in your mind where you are calculating factorial. What is the difference in declaring factorial N as long versus declaring it as unsigned long? Do you agree that unsigned long? Because it is always positive. It does not use two's complement and therefore has one extra bit to represent larger range of positive numbers. Do you all understand this? Unsigned int will get you one more bit in place for representing positive numbers. If you said, instead of unsigned long, if you just said long, it is larger capacity than int. It is a signed int. That means if you have a 32-bit or 64-bit number, one bit will be lost in representing sign. Unsigned will not have that problem. All right. So unsigned long result equal to question mark. We want you to figure out what should be the initial value. Next are simple input statements where you read value of M and N. The variable i is now initialized to something. Then there is a while loop. Now many of you while trying to write this program might not have used while construct which is okay. You can solve the problem in different ways. But this particular program is written using a do while loop. So do something while and that something is a question mark. What is it that you should write here such that this statement do something while i less than N will actually result in M raised to N which is the value of the result. So now think about it. It is useful by the way to look at this program and execute it. You write your answers, draft answers and execute this program with some values of M and N. Do this individually please. Right now no discussion. I want each one of you to just apply your mind to solve this problem. It won't take more than two minutes. Do that. We will have the discussion session. In this code your answer will have three components. First component the initial value that you would like to allocate to result. The second component the initial value that you will assign to i. And the third component is the body of this do loop which will be executed while i is less than N. N and M are input as value. And the answer to be found out is clearly indicated by the output statement. M raised to power N is so-and-so. So what should be there in the question mark? By the way iterative constructs are very fundamental in writing programs which will solve larger problems. So you must have a very clear understanding of how the iteration works and what should be the equivalent constructs. All right. I will now request two things. I will request you to swap your notebooks and check your neighbors answers and discuss. And those of you who have problems, please take help from TAS to discuss these problems. All right. How many people have discussed and found some agreement now? People who agree. And the final solution is a program written by Amit Kumar. So he starts with the value of i equal to zero. And inside the do, he says result is equal to result star M increments the value of i. And while i is less than N, he will keep repeating this. In general, will it find M raised to N correctly? Suppose M is equal to four and N is equal to three, for example. Will it find it correctly? So it looks like this is the way most people think. Most people think that M and N have reasonable values. And therefore for reasonable values, the program may work correctly. But there are possible problems. What is the possible problem? Here is a program written by Manan. His initial value for result is one. His initial value for i is zero. Inside the body, he first checks if N is greater than zero. If it is not, he will not execute this internal part. If N is greater than zero, then he calculates result as result into M. And then he increments i. This will also work correctly. If N is equal to zero, this will not be executed. i will be changed to i plus one. And this will keep on happening till such time that i is less than N. So this program will work correctly except that suppose if I give the value of N as zero initially, then my friend Manan Doshi makes the computer do the Golagiri ten times to keep checking is N zero, is N zero, is N zero. N was zero the first time. It is not going to change later in life. So while the program will work correctly, and I am glad he has taken into account a possible condition when N is equal to zero, which most of you missed. Some people did that but most of you missed. So he has taken cognizance of that. But here are two more solutions. Here is a solution by Akshetish Bajaj, which actually initializes result to one. i is initialized to zero. And inside the two he says if N equals zero, break. See the power of break. If N is equal to zero, you terminate the while iteration completely. Don't need to do it because the result was declared to be one. That is what will be printed. So this is where you can use the break statement effectively. So in this particular case, the while loop will not be executed many times independent of the value of N. If N is equal to zero, you will break out immediately. Here is a similar thing by Raunach. He starts with one here, zero here. And if N is zero, he breaks out. Otherwise the result is result into M. i is equal to i++. So this will continue the loop if M is not. Everything is clear. So while most of you wrote the correct answers, which would work in normal circumstances, and I saw many people religiously checking their answer by taking some sample values of M and N. Very good practice. That is the minimal that you should always do whenever you want to cross check your logic. However, most people forgot to check extreme values of M and N. Indeed, we have assumed that they will be positive values. But what if somebody says minus 23? Now you can't find something raised to minus 23 by this kind of iterative techniques. So what should you do in such case? A validation of input. If such number minus 23 is given, which does not make sense, see out, shout, shout, shout and close. All right. Let's go to the next problem. If M is equal to zero, so what you are saying is zero raised to something will not be found correctly, independent of what you do. So you will have to do something more. And can you do it inside the body of the vile? So he is pointing out another extreme case where even that solution may not perfectly work. I am happy you mentioned that. The point that was being made of this entire exercise of this particular practice problem was that it is not difficult to write simple iterative solutions. You could have used a for loop for example. But what is important is to ensure that your program works even if users give unreasonable input value. There might be mistakes or they might be deliberate or they might genuinely want to find out the answers for that. All right. Here is another problem. Now this problem is actually a special case of the previous problem. Suppose N is a power of 2. Say N is 16. We want to compute the nth power of an integer m by the method of repeated squaring. So we know n square is n into n. m square n raised to 4 is n square into n square. n raised to 8 is n raised to 4 into n raised to 4. So if you want to find out nth power of m, you can just nth power of m. Then knowing this, you can actually multiply the result with result. You get one result. Then you multiply result with result. You multiply result with result. Write an iterative program that takes n and m. Checks whether n is a power of 2 and if so computes m raised to n using repeated squaring. Otherwise the program exists with return code minus 1. Now this is an exercise in programming that you have to do in next 5 minutes. You have to write a program. Please note you have to take two input values. Assume that m is a positive integer so that you don't have to worry about m equal to 0 right now. Because 0 raised to something is a complex situation. So assume that m is positive. You read whatever n. If n is not a power of 2, you declare the input to be invalid and exit with a return code other than 0. Instead of saying return 0, if something something, return 1, return 5, return minus n, whatever. But otherwise the program should execute and find out m raised to n using repeated squaring. So this requires you to actually write the program no more fill in the blanks. Please do not write hash include this that etc. You can assume that you are starting the program with int main. So just write the main program itself. In short, so this is the block in which you have to write your program. You assume that there is an int main and other things. There is a return 0. If the program ends successfully, you will return with a 0. But inside this block, you have to declare the variables. You have to read the values. You have to validate the values. If the valid values are not given, you have to check them with an if statement. And if the values are invalid, you will have to say return something other than 0. Return 1, return 2, return 3. Please note that the return statement is like a break. It breaks out of complete program. The rest of the program is not executed. So please write. This is a suggested program skeleton. Check whether you are writing program in a similar fashion or completely differently. It is suggested that you first read the values of m and n. Check if n is power of 2 using a loop. If so, get c such that n is equal to 2 raised to c. Otherwise return minus 1. And then use repeated sparing c times in a loop to get m raised to n. It is not necessary that all of you must follow this method. But it is useful for all of you to write down such commands before you write the program. So you basically write down the structure of the program in comments only. That you will first do this, then do this, then do this, etc. And then write the program. It is a much better practice to synthesize your program in this fashion because then in your mind you are very clear as to what sequence you are going to solve, sub-problems of the main problem. So observe once again. First you get the value of m and n. Check if n is a power of 2 using a loop. If so, calculate c such that n is equal to 2 raised to c because how many times you have to repeatedly square a value needs to be found out. That is the c. If it is not so, if you cannot find a c which satisfies the equation as equal to 2 raised to c, you just return with minus 1. Otherwise do this. So how many of you were doing something similar? Can you raise your hands? Many people. Good. Some others were perhaps trying to solve the problem differently. That's okay. Anyway, now that this hint is available, those of you who are approaching it differently might want to quickly write a program on these lines. This one does take time. I think people are still writing the program. Just goes to show that when you have to synthesize and construct something, the time taking activity, I am showing two programs here. These are written by neighbors. They discuss with each other. They concluded that both the programs are right although the approach use was different. The program written by Keshav Srinivasan, she actually reads m and n while n is greater than 0. He starts this iteration where he divides n by 2, calculates G as G plus G, G star G, divides n by 2 here. If n modulo 2 is equal to 0, that means only if the number is actually divisible by 2 he does this and else he returns minus 1. This is his output. He will get the correct answer. I will request Keshav Srinivasan and also our friend here, Kumar Ayush. His approach is slightly different. So he is defined in T as n and then repeatedly reduces T by dividing it by 2, keeps a count. So if T is not equal to 1, he returns because that is the way he figures out that it's not power of 2. Otherwise he starts with the result equal to m and he goes up to count because count is what he has already earlier calculated. This will also work. I am sure many of you would have written these programs. I would request both Kumar Ayush and Srinivas and if there are other people who have written a program using similar or different methodology but they have written it correctly, they should test their programs and submit the .cpp file. We would be very glad to include those on the course page. Thank you.