Thursday, August 18, 2011

Repetition Structures

Programs often need to do the same commands several times in a row. Repitition structures, or loops, are designed to do this. There are several kinds of loops.

For loops


The first one we will look at is a for loop.

A for loop contains three elements, a variable with an intial value, a terminal condition, and an increment or decriment statement. Here is an example of a simple for loop that simply outputs the numbers 1 through 10.



for(int i=0;i<=10;i++)
{
Console.WriteLine(i);
}



You could also count backwards:



for(int i=10;i>0;i--)
{
Console.WriteLine(i);
}



The terminating condition can be a variable:



Console.WriteLine("How far do you want to count?");
int number=int.Parse(Console.ReadLine());

for(i=0;i<=number;i++)
{
Console.WriteLine(i);
}



While Loops


For loops are good when you have a specific number or repititions you want to do. While loops are good for when you have an indefinite number of repititions.
Here is an example of a while loop:



int grade=0;
while(grade != 999)
{
Console.WriteLine("Enter a grade. 999 to exit");
int grade = int.Parse(Console.Readline());

}



Do loops


Do loops are like while loops, but the condition is at the end of the loop. This has a subtle effect. A while loop might never execute. If the condition is met before the loop is encountered--if, for instance, grade equaled 999, the program would never execute the while loop. A do loop, on the other hand, always executes at least once.

Here is an example of a do loop:



int grade=0;

do
{
Console.WriteLine("Enter a grade. 999 to exit");
int grade = int.Parse(Console.Readline());

}while(grade != 999);



Infinite Loops


It is important that a loop have a termination point. If not you can create what is called an infinite loop. The only way out of an infinite loop is to stop the program.



for(int i=0;i>0;i++)
{
Console.WriteLine(i);
}



Embedded loops, break keyword


It is important to note that you can nest loops and selection structures as you need. You can have loops inside of loops and ifs inside of ifs. We will see some examples of this in later examples and lectures.

One additional Key words need mention: break. You can use break to exit from a loop before the terminal condition, Here is an example:



for(int i=1;i<1000;I++)
{
Console.WriteLine("enter a name--'exit' to quit");
string name=Console.ReadLine();
if (name.Equals("exit") || name.Equals("Exit"))
{
break;
}
}

No comments:

Post a Comment