Sunday, May 17, 2009

Loopy for loops.

Well, so far we have created programs that basically repeat what we say, "hello world."
or a program that can add 3 to 3, together.  Not bad, but these programs are a bit simplistic.
Like all programs the execute their functions the close.  However to make things more interesting, we need to make a program to will continue to run until we tell it to stop.

How do we do that? We do that with loops.
Loops is when the program restarts after completing its' primary function.  It would go back to designated points in the program, like the beginning of the program or function.  

We will investigate a few of these loop functions. 
The ones we'll look at include the "if", "while" and "for" loops.

The "if" function is not really a loop, but I put it in this category since it does direct the flow of the program.  Essentially you are using "if" to state that if something happens the program will do something else.  Like if the football game is on, then I'll watch.  Of course you can make it a bit more complicated.  If the football game is on, then I'll watch, but if it is not then I'll watch something else.   

Let's look at some code to see this in action.

#include stdio.h                         (our rules or parameters)
int main                                      (beginning of our program)

{int myNumber;                        (declaring my variable)
my Number = 1                       (establishing myNumber equals to 1)

if (myNumber == 2)                       (saying if myNumber is equal to 2)
printf ("myNumber is equal to 2");       (then print "myNumber is equal to 2")
else 
printf ("myNumber is not equal to 2");   (or else print "myNumber is not equal to 2")

return 0;}                     (end program)

"if" and "else" introduces the concept of true and false.  The computer will see either the state is true or the statement is false.  By doing this we can direct the program to do what we want by manipulating what happens when the computer encounters the true/false.



Not bad.  Now we can more deeply into loops, if you do not understand it, re do this part again.  It's important.  


I think I'll split this topic into two post, since
1) It is important
2) It's a big subject.


No comments:

Post a Comment