You are on page 1of 17

Chapter 5: Iteration

Iteration
Void Functions

 Functions that do return any value


 In other languages may be calls sub-programs
 The verb “return” can still be used to end the function
early if needed
 Although it doesn’t actually return a value, because
of Reference and Out parameters, it can make
changes “seeable” by the calling program
Using By Reference Variables

 By Reference parameters are identified preceding


the parameter declaration with “ref”.
 Out parameters are identified preceding the
parameter declaration with “out”.
– Both the calling statement and the method definition must
include the words out or ref
 Although not enforced, it is considered bad form to
use Ref or Out parameters on functions that return
values.
Scope of Variables
 Global/Class/Module
– Variables defined before any method definitions are made
– Should be used VERY SPARINGLY
– Can be accessed by any method at any level within a class.
 Local/Method
– Variables defined within a method (but not inside an if, while, do, for or any other type of block.)
– Can only be accessed by that method . Another method cannot “see” the variables in the first
method . (Except how??)
– Once the method returns, all local variables are destroyed.
– Parameters create local variables (Except when??)
– Local Variables can hide Global Variables, but the Global Variables can be accessed by prefacing
them with ::
 Block
– Variables defined within an if, while, do, for or any other type of block.
– they exist only for the life of the block, and are destroyed when the block is completed.
– C# will not let Block Variables “hide” Local Variables
Control Structures - Repetition

 Two Main Methods


– “for” loop – iterate based on modifying a variable
so that the loop is performed a certain number of
times or until the loop condition is satisfied
– “while” loop – iterate based on the value of an
expression or variable
Let’s look at the “for” loop first

for (initial statement; loop condition; update


statement)
{
statements to execute
}

This is another instance when a single statement can


be specified without the curly braces, but (as you
already know) ALWAYS USE THE CURLY
BRACES!!
A simple “for” loop
 In many cases the “for” loop is used to repeat a routine a certain number of
times:
int i;
for (i=1; i<4; i++)
{
Console.WriteLine(“{0} squared is {1}“,i, i * i);
Console.WriteLine(“{0} cubed is {1}“,i, i * i * i);
}
– What would be the output for the above “for” statement?
 The Three Pieces
– “i=1” initial statement – Executes once at the beginning of the for
– “I<4” loop condition – Is checked before the statements in the for block are
executed. When false, control bases to the statement after the end of the for
– “i++” update statement – Executes before the loop condition is checked EXCEPT for
the first time through the for.
Another example

int i;
for (i=2;i<11;i=i+2)
{
Console.WriteLine(“the number is {0}“,i);
}

 What will the above do?


While Loops

 Come in two different flavors:


– Pre-test loops – a condition is checked BEFORE
any statements are executed.
– Post-test loops – a condition is checked AFTER
the statements are executed.
Let’s Look at the Pre-Test while

while (conditional expression)


{
statement1;
statement2;
statementn;
}

 many times while loops make use of a “loop control variable”


– The variable would be initialized before starting the while loop.
– It would be referenced in the conditional expression.
– It would then be modified in the body of the while.
Simple while Loop

int i = 20;
while (i > 0)
{
Console.WriteLine(“ i now equals {0}“,i);
i = i – 5;
}

What is the output from this while loop.


The post-test while loop

do
{
statement1;
statement2;
statement3;
}
while (conditional expression)
 Using this format of the while, the condition is tested
AFTER the commands are executed.
 This means that the statements are executed at
least one time regardless of the conditional.
Post-Test vs. Pre-Test while Loop

int i = 0; int i = 0;
do while (i > 0)
{ {
Console.WriteLine (“ i now Console.WriteLine (“ i now
equals {0}, i); equals {0}, i);
i = i – 5; i = i – 5;
} }
while (i > 0)

 What happens with each?


break and continue
 sometimes you may want to “get out of a loop” because of an
error, or some other condition is met.
 break – completely stops the current loop
– Often times done to report an error.
– Many times used when doing a look-up. Once the value is found,
stop looking. More on this when we get into arrays.
– Control starts after the end of the current block of code (“}”)
 continue – returns control back to the beginning of the loop
– while would NOT have their condition updated (unless it was done
before the continue)
– for would have the condition updated since it is part of the for
syntax
Nested Control Statement
Multiplication Table

for(i = 1; i <= 5; i++)


{
for(j = 1; j <= 10; j++)
{
Console.Write(“ {0}”,i * j);
}
Console.Writeline();
}
foreach Loops

 A foreach loop enables you to address each element in


an array using this simple syntax:
foreach (<baseType> <name> in <array>)
{
// can use <name> for each element
}
 This loop will cycle through each element, placing it in the
variable <name> in turn, without danger of accessing
illegal elements.
 You don’t have to worry about how many elements are in
the array, and
 You can be sure that you’ll get to use each one in the
loop.
Example

static void Main(string[] args)


{
string[] friendNames = { "Todd Anthony", "Kevin
Holton",
"Shane Laigle" };
WriteLine($"Here are {friendNames.Length} of my
friends:");
foreach (string friendName in friendNames)
{
WriteLine(friendName);
}
ReadKey();
}

You might also like