Engineering 1020 Introduction to Programming Peter King Winter 2010
ENGI 1020: Loops Before we start, two new operators –Increment → ++ Adds one –Decrement → – Subtracts one int x = 5; x--; // x now equals 4 x++; x++; //x now equals 6
ENGI 1020: Loops Very often programs must do repetitive tasks Loops allow us to define a block of code that will execute from top to bottom and then repeat To prevent the code from running forever, we define a condition that tells the loop to stop We could say “do something while something is true”
ENGI 1020: Loops The while loop –One of 3 types of loops in c++ while is a keyword that indicates the start of a loop It contains a condition that must be true for the loop to repeat
ENGI 1020: Loops Buy Lotto ticket Check ticket Didn't Win Go to workRetire My Retirement Plan
ENGI 1020: Loops Buy Lotto ticket Check ticket Didn't Win Go to workRetire My Retirement Plan
ENGI 1020: Loops Structure is same as if statement while (condition){ Statement … Statement }
ENGI 1020: Loops Structure is same as if statement while (condition){ Statement … Statement } If condition is true, statement(s) are executed If condition remains true, statement(s) are repeated
ENGI 1020: Loops Once again the condition is a logical expressions that will be evaluated to either true or false Multiple conditions can be combined with –&& → and –|| → or
ENGI 1020: Loops Structure examples –Factorial –Babylonian estimate
ENGI 1020: Loops Loop Design –What is the task to be repeated? The general case –When should I stop? Based on a value? Based on a count? –What happens when I'm done?
ENGI 1020: Input Conditioning See online notes*