Professional Documents
Culture Documents
Iteration (looping)
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-2
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-3
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-4
Pretest
If the conditional
expression evaluates
to true, statement(s)
performed
If the conditional
expression evaluates
to false, statement(s)
skipped
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-5
5
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-6
int sum = 0;
int number = 1;
while (number < 11)
{
sum = sum + number;
number++;
}
messageBox.show (“Sum of values ”
+ “1 through 10”
+ “ is ” + sum, “Example”);
C# Programming: From
Problem Analysis to Program
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Design
7-7
7
Common problem
◦ Off-by-one error
Loop body not executed for the last value OR
C# Programming: From
Problem Analysis to Program
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Design
7-8
8
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-9
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-12
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-13
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-14
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-15
int counter = 0;
while (counter < 11)
{
Replace MessageBox.Show(counter + “, “ +
above Math.Pow(counter,2) + “, “ + Math.Pow(counter,3));
while
counter++;
loop with
for loop }
below – for (int counter = 0; counter < 11; counter++)
does {
same MessageBox.Show(counter + “, “ +
Math.Pow(counter,2) + “, “ + Math.Pow(counter,3));
}
// Poor Programming.
For (int indexInteger = 1; indexInteger < 10; indexInteger++)
{
indexInteger = 1;
}
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-17