W4 5 Ch3 More Flow Control2
W4 5 Ch3 More Flow Control2
Chapter 3
More Flow of Control
Display 2.12
} while (boolean_expression);
◼ ++ increment operator
◼ Adds 1 to the value of a variable
x ++;
is equivalent to x = x + 1;
◼ -- decrement operator
◼ Subtracts 1 from the value of a variable
x --;
is equivalent to x = x – 1;
Display 2.16
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 10
Infinite Loops
◼ Loops that never stop are infinite loops (problem due to
some error!)
◼ The loop body should contain a line that will eventually
cause the boolean expression to become false and,
hence, exit the loop
◼ Example: Print the odd numbers less than 12
x = 1;
while (x != 12)
{
cout << x << endl;
x = x + 2;
}
◼ Must use this comparison instead: while ( x < 12)
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 11
The Increment Operator
displays 4 3
◼ int number = 2;
int value_produced = 2* (++number);
cout << value_produced << " " number;
displays 6 3
Display 3.10
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 3- 14
III. The for-Statement
◼ sum = 0;
n = 1;
while(n <= 10) // add the numbers 1 - 10
{
sum = sum + n;
n++;
}
◼ sum = 0;
for (n = 1; n <= 10; n++) //add the numbers 1 - 10
sum = sum + n;
Boolean Expression
Display 3.11
◼ Example:
for(int number = 100; number >= 0; number--)
{
// loop body statements
}
◼ Display 3.13 shows the syntax for a for-loop
with a multi-statement body
x++;
◼ Placing a semicolon after nothing creates an
int sum = 0;
for(int count=1; count <= 100; count++)
{
cin >> next;
sum = sum + next;
}
◼ sum must be initialized to zero before the loop body!
ifstream infile;
infile.open("data.dat");
while (! infile.eof( ) )
{
// read and process items from the file
// File I/O covered in Chapter 6
}
infile.close( );
Display 3.15
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 3- 38
Debugging Loops
approximations
execution
◼ Many systems include utilities/tools to help with this
◼ cout statements can be used to trace a value
◼ Can you