90 likes | 236 Vues
Looping . Robert Revaes. Logical Operators. && AND Both have to be true for it to evaluate to be true. || OR One or the other has to be true for it to evaluate to be true. ! NOT Returns the opposite result. Testing the State of an I/O Stream.
E N D
Looping Robert Revaes
Logical Operators • && AND • Both have to be true for it to evaluate to be true. • || OR • One or the other has to be true for it to evaluate to be true. • ! NOT • Returns the opposite result.
Testing the State of an I/O Stream • C++ provides a way to check whether a stream is in the fail state. • ifstreammyIn; • myIn.open(“measures.dat”); • if(!myIn) { • cout << “Can’t open the input file.”; • return 1; • }
The While Statement • Loop executes the same statement over and over, as long as a condition or set conditions is satisfied. • while( Expression) • Statement • Ex: • while (inputVal != 25) • cin >> inputVal; • The statement to be executed each time through the loop is called the body of the loop.
Phases of Loop Execution • The body of a loop is executed in several phases: • The moment that the flow control reaches the first statement inside the loop body is the loop entry. • Each time the body of a loop is executed, a pass is made through the loop. This pass is called an iteration. • Before each iteration, control is transferred to the loop test at the beginning of the loop. • When the last iteration is complete the flow of the control has passed to the first statement flowing the loop, the program has exited the loop. • The condition that causes a loop to be exited is the termination condition.
Loops • Two major types of loops: • count-controlled • Repeat a specified number of times. • event-controlled loops • Repeat until something happens within the loop.
Count-Controlled Loops • Uses a variable we call the loop control variable in the loop test. • Ex: • intloopCount = 1; • while (loopCount <= 10) { • cout << “Hello!” << endl; • loopCount++; • } • Variables used in the way loopCount is used are called counters.
Event-Controlled Loops • Several kinds of event-controlled loops exist: • sentinel controlled • Some special value that that will never show up in normal input. • end-of-file controlled • After a program has read the last piece of data from an input file, it’s in a successful state. • flag controlled • A Boolean variable that tis used to control the logical flow of a program.
Looping Subtasks • Three common tasks: • counting • Keep track of the number of times the loop has been executed. • summing • Sum a set of data values. • keeping track of a previous value • Remember the previous value that was read from input.