Monday, December 19, 2011

Coding lesson: Loops (lesson 12)

In the last lesson I spoke about conditional statements.
Now I'm going to have a look at how we do something repeatedly whilst something is true, or how we do something a finite number of times.

Firstly I'll look at the while function

the while function does something whilst a condition is satisfied.

for example

i = 1;
while (i<=10)
{
printf("i isn't 10!");
}


as i is never modified this statement is always true, and so the loop never finishes.

i = 1;
while (i<=10)
{
printf("i isn't 10!");
i = i+1;
}


you see we're modifying i now so that eventually the condition for the loop to end will be met.


the while statement checks the condition before it is executed.

if we want to run the code at least once, and also again and again whilst a condition is true we use the do function


do
{
printf("what's the password?: ");
scanf("%s", &passwordguess);
}
while(passwordguess!=password);

this will ask you for a password, and would keep running until the condition was false, (until the password guess matched the password)



The other kind of loops that we can use are for loops.
The for loop sets up conditions in the start statement, and runs until the condition is satisfied.

for(start value; condition; modified for each loop)

for
a = 0; /*start a at zero*/
a ==9; /*do this loop whilst this condition is true/*
a = a+1 /*add 1 to the value a on each loop*/

for(i=0;i<=9;i=i+1)
{
printf("A");
}

this prints the letter A ten times.



No comments: