Lecture Transcript While and Do While Statements in C++

Similar documents
Computer Programming

Computer Programming

Computer Programming

LECTURE 5 Control Structures Part 2

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #17. Loops: Break Statement

(Refer Slide Time: 00:26)

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

CS112 Lecture: Repetition Statements

Introduction. C provides two styles of flow control:

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

REPETITION CONTROL STRUCTURE LOGO

Switching Circuits and Logic Design Prof. Indranil Sengupta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

CS 106 Introduction to Computer Science I

Information Science 1

Programming for Engineers Iteration

Compiler Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore

Arrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming

CS 106 Introduction to Computer Science I

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Programming and Data Structure

(Refer Slide Time: 01.26)

(Refer Slide Time: 1:27)

Discussion 11. Streams

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Theory of control structures

(Refer Slide Time: 00:02:02)

Programming in C++ PART 2

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Information Science 1

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

COMP combinational logic 1 Jan. 18, 2016

CS1 Lecture 5 Jan. 25, 2019

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #06 Loops: Operators

(Refer Slide Time: 05:25)

CS61A Notes Disc 11: Streams Streaming Along

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Text Input and Conditionals

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

C++ Programming: From Problem Analysis to Program Design, Third Edition

10/24/2016. We Can Perform Any Computation with an FSM. ECE 120: Introduction to Computing. Find the Minimum Value Among Ten Integers

CS61A Summer 2010 George Wang, Jonathan Kotker, Seshadri Mahalingam, Eric Tzeng, Steven Tang

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Lecture 7 Tao Wang 1

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

CS110D: PROGRAMMING LANGUAGE I

Intro. Scheme Basics. scm> 5 5. scm>

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

CS112 Lecture: Loops

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #13. Loops: Do - While

Computer Programming I - Unit 5 Lecture page 1 of 14

Why Is Repetition Needed?

Laboratory 5: Implementing Loops and Loop Control Strategies

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

introduction to Programming in C Department of Computer Science and Engineering Lecture No. #40 Recursion Linear Recursion

Loops. CSE 114, Computer Science 1 Stony Brook University

(Refer Slide Time: 0:32)

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Programming in C++ Indian Institute of Technology, Kharagpur

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Repetition Structures

LESSON 3 CONTROL STRUCTURES

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

MA 1128: Lecture 02 1/22/2018

More About WHILE Loops

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

Looping Subtasks. We will examine some basic algorithms that use the while and if constructs. These subtasks include

6.001 Notes: Section 17.5

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #19. Loops: Continue Statement Example

Comp 151. Control structures.

Signed umbers. Sign/Magnitude otation

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #33 Pointer Arithmetic

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Control Structures in Java if-else and switch

FOR Loops. Last Modified: 01 June / 1

STREAMS 10. Basics of Streams. Practice with Streams COMPUTER SCIENCE 61AS. 1. What is a stream? 2. How does memoization work?

Computer Programming

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

(Refer Slide Time: 00:01:30)

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

Lecture 1: Overview

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers

Continuing with whatever we saw in the previous lectures, we are going to discuss or continue to discuss the hardwired logic design.

(Refer Slide Time 3:31)

CMPSCI 250: Introduction to Computation. Lecture #7: Quantifiers and Languages 6 February 2012

Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore

Condition Controlled Loops. Introduction to Programming - Python

Lecture 7: General Loops (Chapter 7)

CS102: Variables and Expressions

(I m not printing out these notes! Take your own.)

Transcription:

Lecture Transcript While and Do While Statements in C++ Hello and welcome back. In this lecture we are going to look at the while and do...while iteration statements in C++. Here is a quick recap of some of the relevant topics, we have already studied. We have looked at iteration idioms in programming. We have seen that they are necessary to solve some problems and they are also convenient in other situations. And we have also seen a very brief glimpse of iteration constructs in C++. In this lecture we are going to look at, in more detail, the while and do-while statements in C++. And we are also going to look at the usage of break statements within while and do-while. Now recall this generic iteration construct that we have studied in a previous lecture. So in general, we have a part of the program, that is executed before the iteration. And then we have some initialization, which is iteration specific, and then the actual iteration happens, where we iterate or repeat as long as a logical condition stays true. And what do we iterate over? A block of statements. And in some cases there are some additional instructions that are executed at the end of every iteration. After that, the part of the program that must be executed at the end of this iteration appears. So we had seen earlier, that this part of the code is usually called a loop. This logical condition is also called a loop condition, and the block of statements, along with instructions to execute at the end of every iteration is often called loop body. Now, in C++, we can implement this using the while construct as follows. We could say while (loop condition), block of statements and the optional instructions if any, that had to be executed at the end of every iteration, can be grouped with this block of statements. Similarly, the initialization part can be grouped with the part of the program before iteration. So we have a part of the program before execution of the loop. We have the while loop, within which, we will call both, the block of statements and statements to be executed at the end of every iteration as the body of the while loop, and then we have the part of the program after the while loop. As a flowchart, this can be represented in this manner. We have the part of the program before iteration, part of the program after iteration, and then we check for this loop condition. If it is true, we go through the loop body and again come and check for the loop condition, and at any time the loop condition becomes false when we are doing this check, we can exit from the loop, and execute the part of the program after iteration. So here is simple animation of how control might flow through a while loop. This red dot indicates the control flow. So, the control might flow around the loop a few times and then come out of the loop. Now the points to remember about while loops in C++ are that the loop condition is checked before executing the loop body. So if the loop condition is false, the very first 1

time we are checking it the loop body will not be executed at all. If the loop indeed terminates then the number of times the loop condition is checked is exactly one more than the number of times the loop body is executed. And where does this additional one come from? This additional one comes from the last time the loop condition is checked when it evaluates to false, and then you exit from this loop without executing the loop body. An important point to remember is that if the this loop condition is not changed at all within the loop body, then once you ve entered the loop and you come back and check the loop condition, it will always evaluate to the same truth value as it was in the previous iteration. So if you have entered the loop once, the loop condition must have evaluated to true and in the loop body if you have not changed the loop condition, when you come back and evaluate it again, it will again evaluate to true. And you will again enter the loop body and this will continue forever. You will get, effectively what is called, an infinite loop or a non-terminating program. So you must be very careful when you are using while loops to ensure that the loop body does indeed change the loop condition so that you can finally exit from this loop. Of course there are situations where we might want the program to loop a very large number of times or even infinitely many times. But these are special cases of programs which we will see only later in the course. Now if you look back at the problem that we were trying to solve, when we introduced iteration idioms in programming we had said something like this: That you read the number of students in CS101, read quiz 1, marks of all these students and print their sum, average, maximum and minimum. Now using a while loop, we could solve this and this is kind of obvious to see if I just try to represent the flow of control through this flowchart and if you recall, this is exactly how the flowchart for a while loop looks like. So I am going to read the number of students, initialize aggregates, initialize the counter to 1. Check if the value of this counter which denotes how many quiz marks have been processed so far. If it is less than or equal to the number of students, we go back, ask for the marks, read the marks, update aggregates, increment the count and come back and again check whether we have input the number of students, whether we have input marks for all students, and once we have done that we can exit through this part and compute the average and print aggregates. Now if you go back and look at the flowchart representation for a while loop, it looks exactly like this. Here is the loop condition. Here is the loop body. Here is the program before the while loop. Here is the program after the while loop. So since our control flow matches exactly the pattern, flowchart pattern, for a while loop, we are going to implement it using a while loop. So this is how our C++ program with while might look like. We have our main program and then we have some variable declarations. In this particular case, I have declared the variable count to also be of type float and I will soon explain why that is the case. We have initialized sum to zero during the declaration itself. We ask for the number of students, read the number of students, initialize count to 1.0 Count basically keeps track of the number of students whose marks have been processed so far and then we have this while loop. While count is less than or equal to number of students, we re going to ask for the marks of the student, input the marks, update the values of sum, max and min, increment the count and go around the loop until this logical condition is evaluated to false. 2

Now what does updating sum, max and min mean? We have already seen this in an earlier lecture. To sum, we add the currently read value of marks and if the value of count is 1, we update min and max, straight away by the value of marks. Otherwise we update min and max through conditional expressions. After we are done reading all the student s marks and computing the aggregates, then we compute the value of average which is sum divided by count. And here you will recall, that sum is an integer and since I had declared count to be a float, therefore sum divided by count will be a float data type, and therefore I will be able to retain any fractional part in the average when I do this division. So this was the reason why we had declared count to be of type float. Average is of course of type float and once we have computed the average we can print the average, sum, min and max and then return control back to the operating system. Now if you look at this loop, what is happening inside this loop is that we are reading marks for each student and then these marks were being provided one after the other. They were not being provided all together. So, this is also sometimes called Streaming inputs. But the important point is that we did not remember all the inputs that we have seen so far. We only remembered some aggregates of these inputs: in particular sum, max and min. So what are aggregates in general? This is, these are some kinds of summary of the streaming inputs we have seen so far such that we don t need to remember the actual values of the inputs but we can just use these summary values to compute the final result. And in fact I want to highlight this point here that accumulation or aggregation is key to programming with loops for streaming inputs. You cannot possibly remember all the inputs that are streaming in. So you have to accumulate or aggregate them and using these aggregates you have to compute whatever you want to compute. Now let s look at a variant of our problem. Earlier we had said that we re going to provide the number of students in the class as an input. Now suppose somebody said that: Well, I cannot give that as an input, So what you re required to do is you re required to read off the marks of CS101 students, one at a time, and then if at any point of time I provide -1000 as the input for marks, then you must stop reading. And you must then print out the number of marks entered, their sum, average, minimum and maximum. Now what is the difference of this problem from the earlier version? We do not know a priori how many marks will be entered. Earlier we knew exactly how many students were there and so we could iterate the while loop that many times. In this case, the end of inputs is indicated by a special marks which is -1000. And we ll know, when to stop only after we read this special marks. So how could we modify our earlier C++ program to solve this problem? So once again we declare marks, sum, min, max. Declare average, count. And then we have our little while loop over here. But in this while loop, I do not know when I am going to come out of this while loop until I have actually read the marks. So I am going to put while (true) here. Remember, here we can put any logical expression. True is also a logical constant and hence a logical expression, so I can put while (true). But then notice that what this means is that this condition will never evaluate to false, so the loop condition will be always true which means this looks like an infinite loop. So this is an interesting case where we might want to have an infinite loop and then we will see where we, how we will actually come out of this loop. So we say while (true) because we don t 3

know how many student marks to read. And then we say, Give marks of student, read in the marks, and if the marks is -1000 then I want to exit the loop by some means, otherwise I want to update sum, max and min like I had done earlier, increment count and then loop back again. And finally I have to calculate the average, in this case it is sum divided by count - 1. Because note that, when I exit from this loop by reading -1000 as the marks, I have already incremented the value of count at the end of the previous iteration. So even if I don t execute this loop even once, the value of count is 1, if I execute this loop once, the value of count is 2 and so on. And therefore I need to divide by count - 1 when I m computing the average. And finally I print all of the desired quantities. Now how do we exit from this loop when marks is equal to -1000? It turns out that C++ provides an easy way to do this. In fact that is called a break statement. So I could simply say that if marks is -1000 then break and you would recall that we had also used the break statement when we discussed switch-case statements in an earlier lecture. Now can we really do without breaks? Or are breaks absolutely essential? So it turns out, that we can do without breaks. For example I could say that, let me use an exitflag which is false to begin with. And then I m going to iterate as many times as the exitflag remains false, and then if marks becomes -1000 I ll set this exitflag to true. So at the next time when I go back to check this condition, this condition which is negation of exitflag, evaluates to false. However note that, this incrementing of count must now appear within the else part because if I had a break here then when I exited from the loop, count would not have been incremented. But if I use an exitflag and if this incrementing of count is outside this else block then it would be incremented even after exitflag is set to true. Count would be incremented and only then would I exit this loop. So if I want to preserve behaviour with respect to the previous code, I have to include break within the else block. And using break provides us the convenience of avoiding such annoying complications of putting code that in any case I want to execute before the next iteration is executed. I can now put this code outside the else block if I use the break statement over here. Now recap, this was our while statement in C++. There is a very similar construct that we can use in C++ called do-while. Now in a do-while statement, it s basically the same as the while statement except that this block of the statements is executed at least once. So the flow chart for a do-while statement looks like this: We have the program before iteration, the program after iteration, the loop body, there s a loop condition and then the loop - the same loop body again. And so the control flows like this. So we execute the loop body as many times as is needed but at least once, and then when the condition evaluates to false we come out of the iteration. Now what is the relation between a while and a do-while? If I give you a while loop, it can be easily converted to a do-while by basically checking the loop condition first and if the loop condition is true then I can put the do-while inside. And similarly, if I give you a do-while loop, I can easily implement it as a while loop while making sure that the loop body is executed at least once. And break statements can of course be used in a do-while in the same manner as they are used in a while statement. So what is the comparison between while and do-while? They are almost the same, and it s really left to the programmer s choice. We prefer to use do-while 4

when we know that we re going to execute the loop body at least once. Otherwise we prefer to use while. So in summary, we looked at the while statement in C++, do-while statement in C++ and we also looked at the use of break statements. Thank You! 5