Tuesday, December 1, 2015

The Switch Statement (Case)

Interested in learning the C++ programming language? Try doing it with One Hour a Day.

The switch statement is similar to the if statement in a way that it determines what the program should do depending on certain conditions. It can also be used to control the flow of program. But the way it is built follows a different approach and, unlike the if statement, the switch statement allows for multiple cases or tests to yield the same outcome.

switch (myVariable)
{
    case myFirstCaseValue:
        // do these statements
        break;

    case mySecondCaseValue:
        // do these statements
        break;

    // and so on ...

    case myLastCaseValue:
        // do these statements
        break;

    default:
        // do these statements if no cases were matched (i.e. default behavior)
}

The way the switch traditionally works is like this: you give it an integer expression within the parenthesis (usually a variable). Then the program starts checking for each case that matches that particular case value with the value that was given to the switch statement. If the value of the case matches (that is, is equal to) the same value as the given integer expression in the parenthesis, then it will execute those statements under the case and will ONLY stop when it finds a break statement. The presence of the break is crucial for your switch statement to stop and yield proper behavior, so do not forget to include a break after listing all the statements that should be executed for each case.

Some programming languages other than C++ allow for the expression under switch (expression) to be something other than an integer value. PHP, for instance, allows the use of strings as the argument for the switch statement. With that, your cases can be string values instead of just integer values.

int myIntegerVariable;

myIntegerVariable = 3;

switch (myIntegerVariable)
{
case 1:
  cout << "Action #1" << endl;
  break;

case 2:
  cout << "Action #2" << endl;
  break;

case 3:
  cout << "Action #3" << endl;
  break;

default:
  cout << "Default Action" << endl;

}

Output:

Action #3

First we declare an integer value. Then we assign the value 3 to the integer variable. Next, the switch takes the integer value as its expression and then starts going through the cases. First, it checks the first case: does myIntegerVariable hold the value 1? No, because myIntegerVariable holds the integer 3. It then skips to the next case: does myIntegerVariable hold the value 2? No. Then, the next case: does myIntegerVariable hold the value 3? Yes. Because the values matched, the statements under "case 3:" are executed: it simply displays a message, "Action #3." The program will continue executing statements as long as there is no break statement, so we have to make sure there is a break so the switch statement is terminated and the program goes on to do other stuff.

Had we made the integer variable in the above example hold a case that is not 1, 2, nor 3, then it would default to the default case, which appears at the end, right before the closing brace. In a way, that is like the "else" of an if statement, when all the conditions have failed to be true.

Keep in the mind that the expression given to the switch statement, in C++, has to be an integer, and that the values for the "case X" have to be constant values (no variables allowed!). However, programming languages like PHP allow for the use of strings for the switch expression and cases.

As an example, the following would not work in C++:

string myGreeting;

myGreeting = "Hello";

switch (myGreeting)
{
case "Morning":
  cout << "Good morning to you, too!" << endl;
  break;

case "Hello":
  cout << "Hello, dolly!" << endl;
  break;

case "Night:":
  cout << "See you" << endl;
  break;

default:
  cout << "Good night!!" << endl;

}

Output (the compiler produces an error as output):

switch_statement.cpp: In function ‘int main()’:
switch_statement.cpp:87:21: error: switch quantity not an integer
   switch (myGreeting)

But the above construct would surely work in PHP because it allows strings to be used as the switch expression and case, unlike C++, which only allows integers to be used:

<?php

$myGreeting = "Hello";

switch ($myGreeting) {

  case "Morning":
    echo "Good morning to you, too!";
    break;

  case "Hello":
    echo "Hello, dolly!";
    break;

  case "Night":
    echo "Good night!!";
    break;

  default:
    echo "What's up?";

}

?>

Output:

Hello, dolly!

Switch expressions are typically given an enumeration ("enum") because it makes it easier to understand each case. An enum is like a label given to an integer. It looks like text, but is just a mask behind an actual integer number. For instance, you could make a list of enums that would give represent the integer values 0, 1, 2, 3 like this, using C++:

enum
{
    MY_FIRST_ENUM,
    MY_SECOND_ENUM,
    MY_THIRD_ENUM,
    MY_FOURTH_ENUM
};

With the above, you could use any of the enum items in place of a variable name or value. That would just mask the value behind the scenes. Had we used MY_THIRD_ENUM, we would be actually referring to the value 2 (you start counting from 0 if you use the above enumeration).

Imagine we have a game in which we are checking input from the user. Assume the user presses a key in the keyboard to move the character in the game. It would be either the up, down, left, or right arrows -- there are four cases. So we could make a switch statement to take care of that. But suppose we do not want to explicitly use integers for each case part. Instead, we could use an enum to mask those numbers and make us better understand the code we are writing:

// An enumeration for the keyboard keys
// Each gets associated with an integer value, starting from 0 going to 1, 2, 3, etc.
enum
{
    KEY_UP,
    KEY_DOWN,
    KEY_LEFT,
    KEY_RIGHT
}

// Assume we got the integer value associated with
// the key press inside userKeyPress
switch (userKeyPress)
{
    case KEY_UP:
        // move up
        break;

    case KEY_DOWN;
        // move down
        break;

    case KEY_LEFT:
        // move left
        break;

    case KEY_RIGHT:
        // move right
        break;
}

The above code would translate to exactly the code below. Which one is better to understand? I think the above code is much more intuitive.

// Assume we got the integer value associated with
// the key press inside userKeyPress:
// 0 means up key was pressed
// 1 means up key was pressed
// 2 means up key was pressed
// 3 means up key was pressed

switch (userKeyPress)
{
    case 0:
        // move up
        break;

    case 1;
        // move down
        break;

    case 2:
        // move left
        break;

    case 3:
        // move right
        break;
}

To conclude this article, let us touch upon making multiple cases yield the same outcome. Remember that we had the break statement for every case ending? What if we take that out and stack cases on top of each other, all leading to the same statements? That will do exactly what you would expect: If any of those cases matched, then it would execute those very statements!

Take a look at the code below. Imagine you took some test or a class and you got your grade inside a variable called myGrade. The example below uses a character to check each case. But wait, how come a character can be used if C++ only accepts integer as the expression/case for a switch? Well, that is because a character is actually an integer value. A character is just a mask for an integer value. For instance, the character 'A' can be a representation for the value 65. So the example below will work.

char myGrade = 'C';

switch (myGrade)
{
    case 'A':
        cout << "Excellent!" << endl;
        break;

    case 'B':
        cout << "Great!" << endl;
        break;

    case 'C':
    case 'D':
        cout << "Okay..." << endl;
        break;

    case 'F':
        cout << "You totally failed!" << endl;
        break;

    default:
        cout << "Invalid grade." << endl;
}

Output:

Okay...

The example checks for your grade and goes through each case. Observe we stacked case 'C' and 'D' on top of each other. That is because we want to display the same message if you got either grade C or D. So two cases are yielding the same outcome -- the same message. You can stack as many cases as you want. The secret to this is that once a case is matched, the program keeps executing statements as long as there is no break. Had the case been 'C' in the above example, then it would match there and everything below "case 'C':" would get executed up to the point where a break command was found, signaling the switch operation to terminate. That is, it will walk over to case 'D' and execute the cout with the message "Okay..." even though that case did not match.

Learning the C++ programming language? How about doing it with One Hour a Day.

C++ Arrays

Interested in learning the C++ programming language? Try doing it with One Hour a Day.

Using arrays lets you assemble multiple data into a single entity. Using a primitive data type variable like an int or a double only allows you to store a single value. But when you make that variable an array, then you can store more than one value in one single variable entity.

This article will only consider static arrays -- that is, their size is already pre-determined and cannot be changed once the array has been declared. If you are looking for arrays that can change their size after declaration, those are called dynamic arrays.

In C++, arrays are declared with the following syntax:

data_type arrayName[arraySize];

data_type arrayName[arraySize] = { firstVal, secVal, ..., lastVal };

First, you have to say the type of you data you will be using. That could be any primitive data type such as char, int, float, double or more complex data types such as objects.

After that, give the array a name and tell its size (or length) within the brackets. The size has to be a constant, something that has already been pre-determined. Additionally, you may also want to initialize the array with given values. You do that enclosing each value in a comma-separated-list, within braces (you have to match the number of items with the array size). If you initialize the array right away, you can omit the arraySize and make the compiler guess the size from the number of items in the list. Note that the values have to be all of the same data type because you are declaring an array of a specific type.

As a concrete example:

// Declares an array of integers with 8 elements
int myIntegerArray[8];

// Declares and initializes an array of doubles with 6 elements
double myDoubleArray[6] = { 2.43, 1.24, 1.7, 1.234, 1.9, 3.0 };

// Declares and initializes an array of characters with 3 elements
// (array size guessed from number of items in the comma-separated list)
char myCharArray[] = { 'a', 'b', 'c' };

Note the above array of integers was not initialized, so there is not any meaning value assigned to each element yet.

To go through the items of each array, you usually do a for loop:

for (int i = 0; i < arraySize; i++)
{
    // goes through each array element
}

The loop starts at the first element -- which is always element "0" because array elements are counted from 0 and not one. The last array element is always the array size minus one, so we use just the greater-than operator; the loop stops after "i" becomes the same value as the array size.

As a concrete example:

// Goes through the array of integers (that has size 8) and
// sets each element to current value of i multiplied by 2
for (int i = 0; i < 8; i++)
{
    myIntegerArray[i] = i * 2;

    // Displays the current element value that was just assigned above
    cout << myIntegerArray[i] << endl;
}

Output:

0
2
4
6
8
10
12
14

One thing to keep a watch on is that in C++, you might find yourself accidentaly trying to find an element that is out of bounds in an array. Say your array has 8 elements. The last element has index [7] because you start counting elements from [0]. So the last element would be referred to myArray[7] in this case. But what if you tried to access myArray[8]? Well, this element does not really exist -- you are going out of bounds! It is like you have gone into someone else's property. Your C++ compiler might not complain about that. It will just assume that you are a good person and have not tresspassed into anyone else's property. Watch for this, especially when you do a "for" loop. Always make sure the loop condition uses the right comparison operator (typically you would use <, but you could also use <=) to prevent you from accessing elements beyond the array size.

Let us now look at another example using the last two previously declared arrays:

// Store the array size in an integer variable
int myDoubleArraySize = 6;

for (int i = 0; i < myDoubleArraySize; i++)
{
    cout << "myDoubleArray[" << i << "] has value " << myDoubleArray[i] << endl;
}

Output:

myDoubleArray[0] has value 2.43
myDoubleArray[1] has value 1.24
myDoubleArray[2] has value 1.7
myDoubleArray[3] has value 1.234
myDoubleArray[4] has value 1.9
myDoubleArray[5] has value 3

The above just goes through each element in the array of doubles and displays the corresponding value.

// Store the array size in an integer variable
int myCharArraySize = 3;

for (int i = 0; i <= (myCharArraySize - 1); i++)
{
    cout << myCharArray[i] << endl;
}

Output:

a
b
c

The above goes through each of the three elements in the array of chars. Note how my loop condition is different from the previously used less-than only operator. Here, instead of using i < arraySize, I am using i <= arraySize MINUS 1. That is exactly the same thing as checking for "i" less than the array size. I placed parenthesis between the expression just for emphasis. The loop ends when we reach arraySize minus 1, which is exactly the last element in the array.

Arrays are great when you have large amounts of data and you want to keep them organized and encapsulated into a single variable entity. When you work with arrays, always start counting from 0; the last array element is located at the size of array minus one. Arrays work well with loops because you can handle data conveniently by just using a single statement to take care of each and all of the array elements. Typically, you would use a for loop to go through the elements of an array, either for assignment or just to display their value.

Learning the C++ programming language? How about doing it with One Hour a Day.

The For Loop

Interested in learning the C++ programming language? Try doing it with One Hour a Day.

When you need to perform repeated actions, over and over again, making a programming loop is often the preferred approach. The while and for loops are the most common types of loops. This article will consider the traditional "for" loop, the one derived from the C programming language. Other kinds of for loops are also available, depending on the programming language, and allow you to more conveniently loop over data types such as arrays and objects.

The syntax for the for loop is as follows:

for (initializer; condition; increment/decrement)
{
    // do these statements as long as condition holds true
}

The construct above is often the same for many programming languages. Some programming languages allow you to omit the parenthesis, others need you to place a colon (:) at the end of the first line, and so on. This article will consider the for loop using the C/C++ syntax.

The way the for loop works is it first initializes a certain variable (or variables). Then, it checks the condition to see if it is true. If the condition is true, the statements within the braces are executed. After that, the loop goes on to increment or decrement the loop control variable (which is often the one you had just initialized in the initializer list). Then, it checks for the condition to see if it still holds true. If so, then it goes on to run the statements again. Then it increments or decrements the loop control variable. Then it checks the condition again. This pattern repeats until the condition becomes false, whereupon the loop terminates and the program continues to do whatever it needs to do next.

Let us take a look a concrete example:

for (int i = 1; i <= 10; i++)
{
    cout << i << endl;
}

The above outputs the following:

1
2
3
4
5
6
7
8
9
10

Going the for loop above, first an integer variable named "i" is declared and then initialized with value 1. Then, the condition part is checked. Is 1 <= 10? Yes, it is true, so it executes the statements within the braces. In this case, it only outputs the value of the variable "i." After executing the cout statement, the variable "i" gets incremented: i++, going from value 1 to value 2. After that increment operation, the loop condition is once again checked. If the condition holds true, which it is (2 <= 10), then it goes on to execute the loop statements again. Then i gets incremented, and becomes 3. The condition is again checked (3 <= 10), holds true because the comparison yields a true value. The statements are once again executed, the loop control variable "i" is incremented, the condition is checked. This pattern repeats over and over until the loop condition becomes false, whereupon the loop terminates. In this case, that will be when i becomes 11. So in the end, the loop produces an output that counts from 1 to 10.

For loops are often used to go through the elements of an array:

// An array of integers with 8 elements
int myArray[8] = { 2, 3, 6, 3, 21, 14, 17, 1 };

// To hold the size of the array (i.e. number of elements)
int arraySize = 8;

for (int i = 0; i < arraySize; i++)
{
    cout << myArray[i] << endl;
}

The above outputs all the elements of the array, each in a new line. Note that for arrays, you start counting from 0 and the last element is always the size (or length) of the array minus one. Thus the for loop construct usually follows the format above.

Output:

2
3
6
3
21
14
17
1

In general, the for loop is used when you know specifically how many times to iterate. In the above example, the length of the array was known and it was expected the loop would repeat 8 times. When you do not really know how many times you are going to iterate or you would like some more flexibility and freedom in your loop, you would use a while loop.

Interested in learning the C++ programming language? Try doing it with One Hour a Day.

Monday, November 30, 2015

The While and Do-While Loops

Interested in learning the C++ programming language? Try doing it with One Hour a Day.

Doing repetitive tasks can be accomplished with a programming loop. This article will cover the while and do-while loops. They appear in many different programming languages and often follow the same construct.

Let us first consider the while loop. When you need to keep on repeating the sames tasks, you can put those tasks within a while loop and it will execute as long as some condition is true:

while (condition)
{
    // do these statements as long as the condition is true
}

In the while loop, first the condition is checked. The condition is anything that yields a Boolean value (either true or false). If the condition in the while loop is true, then the statements within the braces are executed. Otherwise, the loop terminates.

To determine when the loop terminates, a loop-control variable is often used. For example, it could be a variable that keeps a count. As long as the count matches a certain criteria, then the loop would keep on running. As soon as that condition no longer holds, then the while loop terminates.

Consider the following while construct in C++:

// Declares an integer variable and assigns it the value 1
int n = 1;

while (n <= 10)
{
    cout << "The value of n is " << n << endl;

    // This line is important as it makes sure the loop is not infinite
    n++;
}

The above code will produce the following output:

The value of n is 1
The value of n is 2
The value of n is 3
The value of n is 4
The value of n is 5
The value of n is 6
The value of n is 7
The value of n is 8
The value of n is 9
The value of n is 10

Going through the code, a variable n is declared and assigned the value 1. Then comes the while loop: first the condition is checked -- is 1 less than or equal to 10? Yes, it is. Since the condition is true, the statements within the braces are executed: the current value of n is displayed and then the value of n gets incremented. The increment part is very important. If we did not have that line, then the loop would going on infinitely. Infinite loops are to be avoided at all costs because they never end! The program above makes sure the loop ends by adjusting the variable n accordingly in every loop iteration. The condition -- that n is less than 10 -- will eventually become false and thus the loop will terminate.

Let us a now consider the do-while loop:

do
{
    // do these statements (at least once)
} while (condition);

The do-while loop works just like the while loop, but the statements within the braces get executed at least once. That is, when the program reaches the do-while, it starts executing the block statements right away without check the condition! Then, after executing the statements within the braces for the first time, it checks for the condition within the while parenthesis. If that condition is true, the loop statements get executed again. This pattern will keep on repeating as long as the condition is true. When the condition finally becomes false, then the loop terminates and the program goes on to do other stuff.

Consider this program in C++:

int m = 2;

do
{
    cout << "The value of m is " << m << endl;
    m++;

} while (m < 2);

First, a variable is declared and defined with the integer value 2.

The program hits the do-while construct and starts executing the statements right away: it displays the value of m, which is 2. Then, it increments m (i.e. increases its value by 1). The variable m now holds the value 3. The condition in the while parenthesis is then checked (for the first time) and evaluates to false because 3 < 2 is not true. The loop then terminates right away.

Output:
The value of m is 2

So the do-while loop executes the statements at least once, even if the condition within the while parenthesis is false right from the beginning.

In general, while loops are often used when you do not exactly know how many repetitions you have to make in order to accomplish a task. Loops that you know exactly how many times to iterate are often implemented using a for loop.

Learning the C++ programming language? How about doing it with One Hour a Day.

The If Statement

Starting out with programming? Be sure to check out The Self-Taught Programmer.

The if statement is used to control the flow of a program. It allows you to determine where to go when you hit an "intersection" in a program. The construct below works on multiple programming languages and follows almost the same syntax (especially in C-based languages).

if (condition)
{
    // do these statements
}

The way the if statement works is like this: first, it checks the conditions within parenthesis. That has to be something that yields a Boolean value (either true or false). If the condition within the parenthesis is true, then the statements within the braces are executed. Otherwise, nothing is done.

Now, if you want something to happen in case the if condition fails, then that is when the "else" clause comes in handy:

if (condition)
{
    // do these statements
}
else
{
    // otherwise, do these statements
}

In this case, if the condition is false, then the statements in the else-block get executed. In essence, when all if conditions fail, the else statements get executed.

If you wanted to check for more than one specific condition, you can use an else-if construct:

if (condition)
{
    // do these statements
}
else if (another condition)
{
    // do these other statements
}
else
{
    // otherwise, do these statements
}

Adding an else-if statement will allow for another condition check. That is, if the condition in the very first if statement is false, then the condition of the next else-if statement will be checked. If that condition is true, then the statements in the else-if block get executed. Otherwise, it will proceed to check the next condition (if there is any other else-if). When all the conditions fail, the else statements get executed.

Thus, with the if-elseif-else construct, you can determine multiple paths for your program to take. You can have as many conditions to check as you want. Just add more else-if statements like this:

if (condition)
{
    // do these statements
}
else if (another condition)
{
    // do these other statements
}
else if (yet another condition)
{
    // do these other statements
}
else if (and yet another condition)
{
    // do these other statements
}
else
{
    // otherwise, if all the above conditions fail, do these statements
}

Keep in mind that only one path may be chosen. If the very first if-condition is true, then those statements within the braces get executed AND nothing else. All the other else-ifs and the else get skipped. If the very first if-condition is false, then the condition for the next else-if statement is checked. If the else-if-condition is true, then the statements within that else-if block get executed AND nothing else. If that condition is false, then it will keep on checking for other else-if conditions. If all the else-if conditions fail (that is, yield false), then the statements within the else-block get executed. That is it. You will only reach the else part when all of the previous conditions have failed and there is no other way to go. In a way, the "else" tells your program where to go or what to do in the last resort.

Here is an example of an complete if statement construct, in C++:

// Checks whether a number is between 1 and 100
// If the number is less than 1, it says "too small"
// If the number is greater than 100, it says "too big"

if (number < 1)
{
    cout << "Your number is too small." << endl;
}
else if (number > 100)
{
    cout << "Your number is too big." << endl;
}
else
{
    // Number is between 1 and 100
    cout << "You are in the right range!" << endl;
}

First it checks if the number is less than 1. If that is the case, then it is certainly out of range. Otherwise, the number is greater than or equal to 1. For the second condition, it checks whether the number is greater than 100. If that is true, then the number is out of range. Once the two conditions have been checked and they both fail, then there is no other choice, but to conclude that the number has to be between 1 and 100. In that case, there is not even a need to check for any condition; just using an else clause will do.

In conclusion, the if statement is used to control the flow of a program. It lets your program makes choices on what path to take based on the given conditions. Multiple choices are not allowed in an if statement. Only one path may be chosen.

Want a more in-depth look into computer programming? Check out The Self-Taught Programmer.