Tuesday, October 5, 2010

this gif is awesome


Friday, October 1, 2010

Week Two Part Two:

We spent today discussing control flow and conditional statements.  This is a huge part of programming, it allows your program to choose which code to execute based on a given expression.  The instructor reviewed if , if-else, if-else-if, and while statements.

To begin, an if statement looks like this:

if (boolean value)

Let's look at the first line; the function of the keyword "if" is obvious.  Inside the parentheses is any expression that evaluates to a boolean value; if the expression is true the code below in the brackets will execute, if not the code within the brackets is ignored by the computer.

Some examples of expressions that could be used in if statements:
(x > 4)
(age >=  22)
(a == b)  <== a equals b
(c != d)  <== c doesn't equal d
(booleanvalue == true)

If-else statements work the same way except if the conditions of the if statement are not met the code in brackets below the keyword else is executed.

If-else-if statements are very similar to if-else statements except the else has its own condition.  This can be repeated any number of times and can be ended with an else or if-else.  This is very useful when you require multiple conditions leading to multiple outcomes.

The while loop is very useful when you want a block of code to execute more than once if a condition is met.  They normally use a counter to control the number of iterations in the loop.  A counter is just a variable that starts at a given number and is increased by one every time the code in the loop is executed until it reaches a value designated to stop the loop.

Here is a sample program using a while loop:

#include <iostream>
using namespace std;

int main ()
     int count;

     cout << "How many iterations would you like?" << endl;
     cin >> count;

     while ( count > 0)
          cout << "Hello Blogger Community" << endl;
          count = count - 1; //this can also be written count--

     cout << "That is all." << endl;

     return 0;

Notice that there is no semi-colon placed after the declaration of the while loop.  This is also the case for all variants of the if statement.

I hope I'm doing OK with this blog.  Any constructive criticism is more than welcome!