Sunday, January 22, 2012

Introduction to C++ Functions


This blog assumes that the reader understand how to create a C++ program containing a single statement that displays the phrase "Hello World!" Therefore this blog focuses solely on functions and does not explain the main function nor the class libraries.

A function is a group of C++ statements that collectively perform a specific well defined task. Functions can be executed repeatedly throughout a program. The advantage of a function is that the programmer does not have to repeat the C++ statements each time the task needs to be performed.

First, I will explain each statement in the example, then I will present the complete tested and debugged example.

/* The first statement lists the iostream class. */

#include <iostream>

/* The second statement invokes namespace. */

using namespace std;

/* For more details on iostream and namespace see my blog titled
An Introduction to C++ Programming. */

/* Now we can insert our function header. You can name your function any name you like. I recommend that the function name describes what the function does. This will make it easier to understand the program when you come back to modify it. The word void at the far left of the function name means that the function does not return anything to the calling function. In this example, the calling function is the main function. The word void in the parenthesis means nothing is passed to the function from the main function. */

void Display_Hello_World(void)

/* The beginning of the function is defined by an opening curly bracket. */

{
/* The function only has one statement. That statement displays the words "Hello World" on the monitor. The cout function is defined in the iostream class library. */

cout << "Hello World!" << endl;

/* The end of the function is defined by a closing curly bracket. */

}

/* The main function invokes the function name Display_Hello_World. */

int main (void)
{
Display_Hello_World();
}

/* A function can return a value. The following function declares an integer, assigns a value to that integer and returns the integer value to the calling function. */

int FReturn_A_Value (void)
{
int a_value = 5;
return a_value;
}

/* The main function calls the FReturn_A_Value funtion and  and stores the value returned in my_value. */

int main (void)
{
int my_value;
my_value = FReturn_A_Value();
}

/* A variable can be passed to a function. The function FPass_A_Variable accepts an integer from the main function and displays it. */

void FPass_A_Variable(int my_value)
{
cout << my_value << endl;
}

/* The main funtion declares an integer, assigns the integer the value of 5 and passes the value to the function FPass_A_Variable. */

int main (void)
{
int value = 5;
FPass_A_Variable(value);
}

We can implement each defined task in a function. The function makes the program easier to read and easier to troubleshoot. The name of the function should describe what the function does. Likewise, the name of the variables should describe those variables. We know that the variable is an integer. The variable name should describe what the variable is.

An example is:
int temperature;

Here are examplies of function names
Read_Temperature().
Test_temperature_range().
Display_temperature().
Display_warning_message().

Note how easy it is to understand each function does.
The more clearly one describes variables and functions, the easier it is to read and understand the program.
The function should execute a single well defined task. The inputs and outputs of each function could be defined in the comments before the actual function.

/*****************************************************************
Function name
Inputs: Description of each input
Outputs: Describe the each output
Description: Describes what the function does
*********************************************************************/
/* Place function here */

The advantage of these comments is the time it saves if the programmer should have to modify the program months or years after the program was designed.

Friday, January 13, 2012

Basic Concepts of Computer Programming

 

I originally published this article on Yahoo Voices under the pen name John Mario.

This article is intended for those who have not had any exposure to computer programming and have no knowledge of electronics. This article does not define how to write a program in a specific language. It only covers the basics.

In order to write a computer program, you need a compiler. A compiler allows you to use a specific set of instructions to create a computer program and then convert that program into machine language.

Each compiler is for a specific programming language. A programming language is a specific set of instructions available for use in any program. Two very popular programming languages are Visual Basic and Visual C++. The modern compilers provide the user with an editor that allows the user to type in the program. You would type selected instructions in a specific order to perform a specific task. For example, you might want to collect information from the user and display that information on the monitor.

One instruction found in compilers is the print instruction.

If you wrote a program to display the phrase "Hello World," you would use the print instruction.

It would look like this:

print "Hello World!"

Each compiler may require a different syntax for the print instruction. For example: the C++ compiler requires a semicolon at the end of each instruction. Hence in C++ you would type

print "Hello World!";

There are other requirements for a complete C++ program to print "Hello World." But the exact contents of the complete program in C++ is beyond the scope of this article.

After writing and saving your program, you have to build your program. Building a program means converting the program to machine language. The resulting machine language file contains binary codes. When you build a program, the program may list syntax errors. These errors are instructions that are typed in wrong. They may be missing punctuation marks or they may contain unrecognized words.

When you execute the program, the binary code is converted into voltage levels that are applied to the electronics inside your computer to cause the computer to perform a specific action.

After you build the program, you have to test it. You start by executing the program. If the program does not run correctly, you have to examine the program to find out what is wrong. Debugging a program is an art by itself.

Learning programming is a challenging task that will consume a significant portion of your time. I highly recommend taking a course in school. However, if you prefer to learn on your own, you might join a programmer's forum on the web.Then you can ask questions in the forum about which is the best compiler for you and which books they recommend. Your best bet is to go to your local book store where you can read a few pages of the book to find out if you can understand it.

Reference:

My experience as an embedded systems software engineer.

Cplusplus: Understanding Arrays, Character Strings, and Pointers



I originally published this article on Yahoo Voices under the pen name John Mario.

We learned in earlier lessons that a variable is the name of a memory location that holds data. In computers, we also need a way to find that memory location. In real life, the US Post Office finds our residences via our address. Each memory location in a computer is assigned a numeric address.

Before we learn about pointers, arrays and strings, let's become familiar with the American Standard Code for Information Interchange (ASCII).

The ASCII code is a set of numbers that all keyboard characters are converted to. You can find the ASCII code at

http://www.asciitable.com/

When you press and release a key of your keyboard, the actual character shown on the key is not stored in memory. Instead, a number is stored in memory. That number is the ASCII code for that character.

The ascii code for the character 'a' is 141 in octal. The following program assigns the character 'a' to my_character and displays it. Then it assigns the ASCII code octal value 141 to my_character and displays it. The ASCII octal value 141 is displayed as the character 'a'

/**** place the include iostream statement here ****/

using namespace std;

int main (void)

{

/* Declare a character variable */

char my_character;

/* Assign my_character the letter 'a' */

my_character = 'a';

/* This statement displays the letter 'a' */

cout << my_character << endl;

/* Assign my_character the ASCII code for the letter 'a' */

/* The forward slash tells the compiler that the ASCII code is used instead of the letter. */

my_character = '\141';

/* This statement also displays the letter 'a' */

cout << my_character << endl;

} /* end of main function */

/******* End of program *******/

In C++, the ampersand sign means the address of when a variable name is appended to it.

&my_variable means 'the address of my_variable. A pointer points to a variable. In other words, a pointer holds the address of a variable.

The following program displays an integer in two ways. First it displays the integer via the variable my_variable which holds the integer. Then it displays the integer via the pointer my_pointer that points to my_variable.

**

/**** place the include iostream statement here ****/

using namespace std;

int main (void)

{

/* Lets declare a variable that holds an integer */

int my_variable;

/* Now lets declare a pointer*/

/*The asterick denotes a pointer to

a variable of type integer. */

int *my_pointer;

/* The pointer is declared but it does not point to any variable. Let my_pointer point to my_variable */

my_pointer = &my_variable;

/* Lets assign a value to my_variable */

my_variable = 5;

/* Display the integer stored in my_variable. */

cout << my_variable << endl; /* Displays the integer 5 */

/* Use the pointer my_pointer to display the integer in my_variable. */

cout << *my_pointer << endl; /* Displays the integer 5 */

} //end of main function

/******* End of program *******/

ARRAYS

An array is a group of contiguous memory locations holding a string of values. The following program creates an array of integers named my_array[2]. The number 2 means there are two locations in this array. Those locations are my_array[0] and my_array[1]. The program places integer values in each location and then prints them one at a time.

**

/**** place the include iostream statement here ****/

using namespace std;

int main (void)

{

/* The following statement declares an array of two memory locations designated as holding integers. Each location holds one integer. The two memory locations are my_array[0] and my_array[1] */

int my_array[2];

/* Assign the value 4 to the first location of my_array */

my_array[0] = 4;

/* Assign the value 3 to the second location of my_array */

my_array[1] = 3;

/* Display the contents of the first location of my_array */

cout << my_array[0] << endl;

/* Display the contents of the second location of my_array */

cout << my_array[1] << endl;

} // end of main function

/******* End of program *******/

The following program is the same as the last program except that the integers are assigned to my_array in the declaration of my_array.

/**** place the include iostream statement here ****/

using namespace std;

int main (void)

{

/* The following statement declares an array of two memory locations designated as holding integers.and assigns the value 4 to the first location of the array and the value three to the second location of the array */

int my_array[2] = {4, 3};

/* Display the contents of the first location of my_array */

cout << my_array[0] << endl;

/* Display the contents of the second location of my_array */

cout << my_array[1] << endl;

} // end of main function

/******* End of program *******/

We can also create an array of characters. The following program creates an array of characters. The array is named my_greeting. The program sets up a pointer to the array my_greeting and uses the pointer to display the greeting. The array of characters must be terminated with a null character. The null character denotes that all the characters have been printed.

**

/**** place the include iostream statement here ****/

using namespace std;

int main (void)

{

char *my_pointer;

/* declare an array that will contain five characters

and a null character. */

char my_greeting[6];

/* my_pointer must point to my_greeting */

my_pointer = my_greeting;

/* We can fill the array locations one by one with the following inefficient code */

my_greeting[0] = 'h';

my_greeting[1] = 'e';

my_greeting[2] = 'l';

my_greeting[3] = 'l';

my_greeting[4] = 'o';

/* We must add a null character to tell the compiler

that this is the end of the array */

my_greeting[5] = '\0';

/* Print only the first character of the array */

cout << *my_pointer << endl;

/* Print the whole array */

cout << my_pointer << endl;

} /* end of main function */

/******* End of program *******/

The above program could have been written using two C++ statements in the main function.

The following program is the same as the previous program except that it defines the characters in the pointer declaration. Note that the pointer declaration include the characters "hello." This is called a character string. When defining the character string in this manner, the programmer need not worry about the terminating null character.

/**** place the include iostream statement here ****/

using namespace std;

int main (void)

{

/* We could save time by filling the array in the declaration of the pointer */

const char *my_pointer = "hello"; /* generates compiler error */

/* "hello" is a character string that exists in the array my_greeting[]

my_greeting[0] is pointed to by the pointer my_pointer. */

/* Display the message "hello" */

cout << my_pointer << endl;

/* Print only the character 'h" */

cout << *my_pointer << endl;

} //end of main function

/******* End of program *******/

The following program uses the variable i as an index into my_array. Then it uses the pointer my_pointer to display the contents of my_array.

**

/**** place the include iostream statement here ****/

using namespace std;

int main (void)

{

/* declare integer i and set it equal to 0. */

int i = 0;

/* declare a pointer */

char *my_pointer;

/* Declare an array of two characters */

char my_array[3];

/* my_pointer must point to my_array */

my_pointer = my_array;

/* Use the value of i as the index into the array. */

/* Save the character 'H' in my_array[0] */

my_array[i] = 'H';

/* Increment i by 1 */

i++;

/* Save the character 'e' in my_array[1] */

my_array[i] = 'e';

i++;

/* Save a null character in my_array[2] */

my_array = '\0';

/* Display my_array */

cout << my_pointer << endl;

} /* end of main function */

/******* End of program *******/

We can also increment and decrement pointers.

The following program declares an array my_array and then uses the pointer my_pointer to point to specific locations of the array and store integers in the array.

**

/**** place the include iostream statement here ****/

using namespace std;

int main (void)

{

/* declare the index variable i */

int i = 0;

/* declare the character array my_array */

char my_array[3];

/* declare the pointer my_pointer */

char *my_pointer;

/* my_pointer must point to my_array */

my_pointer = my_array;

/* Store an 'H" in my_array[0] */

*my_pointer = 'H';

/* point to my_array[1] */

my_pointer++;

/* Store an 'e' in my_array[1] */

*my_pointer = 'e';

my_pointer++;

/* store a null character in my_array[2] */

*my_pointer = '\0';

/* Reset the pointer to the first location of the string */

my_pointer = my_array;

/* Display the character string in my_array. */

cout << my_pointer << endl;

} /* end of main function */

/******* End of program *******/

The following programs shows a property of the increment operator. The statement

my_array[i++] = 'T';

places the letter T in my_array[i] and then increments i.

The statement

my_array[++i] = 'T';

increments i and then stores the letter T in my_array[i].

After placing the characters 't', 'e', 's', 't' and a null character in the array. The program displays the word text.

/**** place the include iostream statement here ****/

using namespace std;

int main (void)

{

/* declare a character pointer */

char *array_ptr;

/* Declare a array of characters */

char my_array[7];

/* Declare and initialize the array index i */

int i = 0;

/* The pointer must point to the array *?

array_ptr = my_array;

/* store the character 'T' in my_array[i] and then increment i. */

my_array[i++] = 'T';

/* Store an 'e' in my_array[1] */

my_array[i] = 'e';

/* This statement increments i and then stores a the character 's' in my_array[i] */

my_array[++i] = 's';

i++; /*increment i */

/* This statement stores the character 't' in my_array[i] and then increments i. */

my_array[i++] = 't';

/* Insert a null character in my_array */

my_array[i] = '\0';

/* display the contents of my_array */

cout << array_ptr << endl;

} /* end of main function */

/******* End of program *******/

References: My own experiences during my career as a embedded systems software engineer.

The book 'C++ THE COMPLETE REFERENCE' by Herbert Schildt.

ISBN 0-07-222680-3


The Cplusplus Programming Language Switch Statement

I orignally published this article on Yahoo Voices under the pen name John Mario.

This Tutorial covers the C++ switch statement.

The basic form of the switch statement is shown below. The names of the variables in this switch statement describe their function. The case_identifier_value defines which case will be executed. Each case begins with a case statement ends with a break statement as shown below. Each time the switch statement is called, only one case is executed. The C++ statements between the case statement and the break statement comprise the response for that particular input. The case_identifier_value can be an integer or a letter of the alphabet. If the switch statement receives an invalid case_identifier_value, the default case is executed. The default case starts with 'default:' and ends with a break statement.

BASIC FORM OF SWITCH STATEMENT

switch (case_identifier)

{

case(case_identifier_value) // case for a specific value of case_identifier_value

// case_identifier_value value must be number or letter

//C++ statements for responding to a specific case_identifier_value

break; // end of case

break;

// one case exists for each

// valid case_identifier_value

default:

// The default case contains C++ statements

// that respond to

// invalid case_identifier_values

break; //end of default case

}

FIRST C++ PROGRAM CONTAINING SWITCH STATEMENT

A sample program containing a switch statement is shown below. In this program, the switch statement excutes a case based on an integer.

// place include iostream statement here

using namespace std;

int main(void)

{

int count; //declare the variable count

cout << "Type a number less than 6 " << endl; //instruct user

cin >> count; // await keyboard entry

switch(count)

/******************************

This switch statement executes

one of the cases below based on the

value of count.

Note that each time the switch statement

is executed only one case is executed

or the default case is executed.

******************************/

{

case 0: //If count equals 0, this case is executed

cout << "count = " << count << endl; //display count of 0

break; // exit from switch statement

case 1: //If count equals 1, this case is executed

cout << "count = " << count << endl; //display count of 1

break; // exit from switch statement

case 2: //If count equals 2, this case is executed

cout << "count = " << count << endl; // display count of 2

break; // exit from switch statement

case 3: //If count equals 3, this case is executed

cout << "count = " << count << endl; //display count of 3

break; // exit from switch statement

case 4: //If count equals 4, this case is executed

cout << "count = " << count << endl; // display count of 4

break; // exit from switch statement

case 5: //If count equals 5, this case is executed

cout << "count = " << count << endl; // display count of 5

break; // exit from switch statement

default: // default case: execute if count is not between 1 and 5

cout << "count out of range" << endl; // display count out of range

break; //exit switch statement

} //end of switch statement

} // end of main

SECOND C++ PROGRAM USING SWITCH STATEMENT

The switch statement can also execute cases based on a character input. In the following program we use the switch statement to accept one of the following letters: a, b, c, d, e.

//place include iostream statement here

using namespace std;

int main(void)

{

char answer; //declare the variable answer

cout << "Type in one of the first five letters of the alphabet" << endl;

cin >> answer; // await keyboard entry

switch(answer) //Execute case based on answer

// Note that each time the switch statement

// is executed only one case is executed

// or the default case is executed.

{

case 'a': //If answer equals 'a', this case is executed

cout << "answer = a" << endl; //display answer

break; // exit from switch statement

case 'b': //If answer equals 'b', this case is executed

cout << "answer = b" << endl; // display answer

break; // exit from switch statement

case 'c': //If answer equals 'c', this case is executed

cout << "answer = c" << endl; //display answer

break; // exit from switch statement

case 'd': //If answer equals 'd', this case is executed

cout << "answer = d" << endl; // display answer

break; // exit from switch statement

case 'e': //If answer equals 'e', this case is executed

cout << "answer = e" << endl; // display answer

break; // exit from switch statement

default: // default case: execute if answer is not a, b, c, d or e

cout << "invalid answer" << endl; // display error message

break; // end of default case

} //end of switch statement

} //end of main function

A PRACTICAL USE OF THE C++ SWITCH STATEMENT

The following is a practicle example. The actual C++ statements in each case are replaced with an explanation of what those C++ statements do.

//Place include iostream statement here

using namespace std;

int main(void)

{

int command_input;

cout << "select item number from menu" << endl;

cout << "1 Print list of employees" << endl;

cout << "2 Print list of employee wages" << endl;

cout << "3 Print list of new employees" << endl;

cout << "4 Print list of managers" << endl;

cout << "5 Print list of manager salaries" << endl;

cin >> command_input;

switch (command_input)

{

case 1:

//The C++ statements for this case

// print a list of employees

break;

case 2:

//The C++ statements for this case

//print a list of employee wages

break;

case 3:

//The C++ statements for this case

//prints a list of new employees

break;

case 4:

//The C++ statements for this case

//Prints a list of managers

break;

case (5):

//The C++ statements for this case

//Print a list of manager salaries

default:

//The C++ statements for this case

//responds to the invalid command_input

break;

} //end of switch statement

} //end of main function

References:

My own experiences during my career as a embedded systems software engineer.

The book 'C++ THE COMPLETE REFERENCE' by Herbert Schildt.

ISBN 0-07-222680-3



C++ EXPRESSIONS AND OPERATORS



I originally published this article on Yahoo Voices under the pen name John Mario.

THE IF STATEMENT

The simplest of the C++ control statements is the IF statement. This article will use the IF statement to explain the use of expressions and operators.

The best example of the IF statement are the ones written in plain English. Note that the examples are enclosed in double astericks.

The basic form of the IF statement is

'if condition then action

else some other action'

The condition is an expression containing variables and operators.

Here is an example written in the Englsigh language.

**

If it is raining then bring the umbrella

Else leave the umbrella home.

**

The condition is 'is it raining.'

The possible reactions are bring the umbrella or don't bring the umbrella.

In the C++ programming language, the condition is always placed in parenthesis.

THE == OPERATOR

The first operator we will consider is the operator ==.

This operator is used to determine if two values are equal. It is used in the IF statement within the following C++ program.

**

char answer; // The variable answer will contain a character

cout << "Will it rain today? " << endl; //Ask the user to a question

cout << "Type y for yes or n for no" << endl; // Give user choice of answers

cin >> answer; //Accept answer from user

If (answer == 'y') //test answer of 'y'

cout << "Bring Umbrella" << endl; // It will rain. Tell user to bring umbrella

Else

cout << "Leave umbrella home" << endl; //It won't rain. Leave umbrella home

**

The double equal sign indicates a comparison.

If the user makes the mistake of using a single equal sign in the expression , the ELSE statement will never be executed.

**

Example:

If (answer = 'y') // Error. Expression will assign 'y' to answer

cout << "Bring Umbrella" << endl; // Will always execute.

Else

cout << "Leave umbrella home" << endl; //Will never execute.

**

The reason is the single equal sign means assign the variable to the left of the equal statement the value on the right of the equal statement. This IF statement would unconditionally assign the character 'y' to the variable 'answer.'

THE != OPERARATOR

The operator != means 'not equal to.'

answer != 'y'

means answer is not equal to 'y'

The IF statement

if (answer != 'y')

cout << answer;

displays answer if the variable answer does not contain the character 'y'

THE > OPERATOR

The operator > means 'is greater than.'

The expression

answer > 4

in the IF statement

if (answer > 4)

cout << answer;

tests the value in the variable answer for a value greater than 4.

If the variable answer has a value that is greater than four than the value is displayed.

THE >= OPERATOR

The operator >= means 'greater than or equal to.'

The instruction

if (answer >= 4)

cout << answer;

means "if answer is greater than or equal to four, display answer."

THE <= OPERATOR

The operator <= means 'less than or equal to.'

The instruction

if (answer <= 4)

cout << answer;

means "if answer is less than or equal to four, display answer."

THE && OPERATOR

The && operator means AND.

If condition one exists and condition two exists do this.

Both condition one and condition two must be true.

The statement

if ((expression one) && (expression two))

means "if expression one is true AND expression two is true.

The && operator allows us to test for a range of values. Consider the following C++ program:

**

int answer; //answer will hold an integer

cout << "Type in one of the integers 4, 5, 6, 7, or 8 "; //ask user for integer value

cin >> answer; // Accept answer from user.

if ((answer >= 4) && (answer <= 8))

cout << "answer = " << answer << endl; //Answer within rage. Display answer.

else

cout << "answer out of range." << endl; //Tell user the answer is out of range.

**

THE || OPERATOR.

The || operator means 'or.'

The expression 'condition one OR condition two' means 'if either condition is true.'

The statement

if ((condition one) || (condition two))

cout << answer;

means " if condition one is true or condition two is true, display answer.

The || operator allows us to testing for a one of two values. Consider the following program.

**

char answer; //answer will contain a character

cout << are you at least 18 years old? (y/n)"; //ask user a question

cin >> answer //Accept answer

if ((answer == 'y') || (answer == 'n'))

cout << answer; //Answer is 'y' or 'n' Display answer.

Else

cout << "Error! Enter y for yes or n for no" << endl; // answer is not acceptable.

**
References: My own experiences during my career as a embedded systems software engineer.

The book 'C++ THE COMPLETE REFERENCE' by Herbert Schildt.

ISBN 0-07-222680-3


INTRODUCTION TO THE C++ PROGRAMMING LANGUAGE



I orginally published this article on Yahoo Voices under the pen name John Mario.

The purpose of this series of articles is to explain the C++ programming language to the reader who wants to learn C++.

OVERVIEW OF THE C++ PROGRAMMING LANGUAGE

The C++ language is a versatile, structured programming language with extensive libraries of functions available for the programmer's use. The language is used for console applications, windows applications and application in modern appliances and industrial equipment.

WHAT IS A PROGRAM?

A program is a series of steps the computer performs to attain a specific result of set of results. The steps are written in a specific programming language such as C++. The programming language consists of a number of instructions that can be used in the design of any computer program. Every C++ instruction is terminated with a semi-colon.

A console application is a program that uses the old DOS-like screen. A console application does not use windows. Each output is sent directly to the monitor.

C++ LIBRARIES

Libraries contain functions for the programmer's use. A function is a routine that performs a specific operation. For example, the square root function takes the square root of a number. The C++ programming language includes a class library and a standard function library derived from the C language. A class contains an encapsulated group of related functions and variables. Variables are defined in this article. Classes and functions will be discussed in future articles.

In order to display anything on the monitor, we include the library class iostream. The library class iostream is a library of generic input and output functions provided for the programmer with any C++ compiler. To access the functions in iostream we need an include statement. The include statement of the library class iostream. begins with the pound sign.

# include < iostream > // include the library class iostream.
// note that spaces are not allowed between < and >
// spaces were included to overcome a text editor problem.

NAMESPACE

Namespace prevents conflicts between programmer functions and library functions having the same name. This statement should be inserted below the include statement in every C++ program.

using namespace std;

Without the statement 'using namespace std', the compiler will return numerous errors.

THE MAIN FUNCTION

Every C++ program must have a 'main' function. The main function is not part of iostream. The main function defines the start of the program. The 'main' function is implemented as follows:

int main (void)

{

// The program is typed in between the two curly brackets

}

Let's examine the 'main' function.

int main (void)

The keyword int means the function 'main' will return an integer value. An integer value is a whole number. In the program at the end of this article, a zero is returned.

The space between the parentheses is used to pass information to a function. (void) means no variables are passed to the 'main' function.

COMMENTS

Any program should also contain comments. Comments help a new programmer understand the program and are often helpful when modifying an old program.

The C++ compiler recognizes any line that begins with a double slash // as a comment.

// This line is a comment

A comment could also start with /* and end with */

/*

This line is a comment

This line is another comment.

There is no need for two slashes because we are using the slash and asterisk

*/

If you have a comment that is several lines long, you might try this technique so your comments clearly stand out

/*******************************************************
Add your long comment here.
It could be a long as you want.

********************************************************/

KEYWORDS

The C++ language uses keywords for types of data. The keywords int, double, float and char are common keywords used in programs. The keyword int means integer.

examples:

59 is an integer

A double is a number containing a decimal point

54.35 is a double

A floating point number is a number like 5.3 x 10^-2

5.3e-2F is a floating point number. The keyword for a floating point number is float. 'e-2' means x 10^-2 wherein ^ means 'raised to the power of'

Char stands for character. A character is any key on your keyboard. A single character is enclosed in single quotation marks

'a' is a char.

'1' is a char.

';' is a char.

VARIABLES

A variable is a name assigned to a memory location. A declaration defines exactly what is stored in that memory location.

In the following instruction, the keyword 'int' declares that the variable first_value will hold an integer. Only integers can be stored in the memory location named first_value.

int first_value;

The following instruction declares that the variable my_number will hold a double.

double my_number;

The following instruction declares that the variable my_floating_pt will hold a floating point number.

float my_floating_pt;

The following instruction declares that the variable my_character will hold a character.

char my_character;

ASSIGNMENT STATEMENTS

An assignment statement assigns a value to a variable.

Consider the following examples;

int a;

a = '1'; //this line will deliver an error because

// '1' is a character

a = 1; // this instruction places the integer 1 in the memory location named a.

char b;

b = '1'; // this instruction places the character '1' in the memory location named b.

Instead of using one instruction to define each variable, we can use one instruction to define all three variables by listing the variables and separating them with commas.

int first_value, second_value, sum_of_values;

To store a value to a memory location, we use an assignment statement

Consider the following instructions.

int first_value;

first_value = 5; // The integer 5 is stored is stored in

// the memory location named first_value

The above two statements can be combined.

The following statement declares the variable first_value to hold an integer and assigns it a value of 5.

int first_value = 5;

First_value can be changed inside the program

Example:

#include < iostream > // spaces are not allowed between < and >

using namespace std;

int main (void)

{

int ax = 4;

// Later in the program, the value of ax is changed.

ax = 5; //okay

}

CONSTANTS

A constant is a value that cannot be changed. The keyword for constant is CONST. Consider the following declaration:

const char my_constant = 'a';

This statement declares that the variable my_constant will hold a the character 'a'. If the programmer tries to change the character, the compiler will return an error.

Example:

#include < iostream > // note: spaces are not allowed between < and >
// spaces were included to overcome text editor problem.

using namespace std;

int main (void)

{

int a;

a = 5;

const char my_constant = 'a';

my_constant = 'b'; //error: cannot change a constant.

}

COUT AND CIN FUNCTIONS

The cout function is a member of the iostream class library.

'Cout' sends messages to be displayed on the monitor. Consider the following short program.

#include < iostream > // spaces are not allowed between < and >

using namespace std;

int main (void)

{

int a, b, c;

a = 5,

b = 10;

c = 20;

cout << a << ' ' << b << ' '<< c << endl;

cout << "end" << endl;

}

The output of this program excerpt would be

5 10 20

end

The cin function is also a member of the iostream class library.

The cin function reads an entry from the keyboard and stores it in a memory location.

int my_number;

cin >> my_number;

The instruction cin >> my_number reads an integer from the keyboard and stores it in the memory location named my_number. If the user types anything but an integer, the cin function will fail.

PERFORMING ADDITION

The following instruction adds the values in first_value and second_value

and stores the result in sum_of_values.

sum_of_values = first_value + second_value;

WRITE PROGRAM IN THE ENGLISH LANGUAGE

Let's consider a program that adds two integers and saves the result. An integer is a whole number.

First we'll state the individual steps of the program in English.

A variable is the name of a memory location that contains data. When we declare a variable, we must declare what type of data that variable will contain.

Define three variables as integers. Name them first_value, second_value and sum_of_values.

Prompt the user assign integer values to first_value and second_value.

Add first_value and second_value and store the sum in sum_of_values.

Display first_value, second_value and sum_of_values.

An explanation of this sample program follows the program.

A SAMPLE C++ PROGRAM

#include < iostream > // spaces are not allowed between < and >

using namespace std;

int main (void)

{

// Define the variables first_value, second_value and sum_of_values as integers

int first_value, second_value, sum_of_values;

//Display the phrase "Summation of Integers" on the monitor.

cout << "Summation of Integers" << endl;

// 'endl' means it is the end of the line.

//Prompt the user to enter the first integer

cout << "Enter first integer: ";

//Read the first integer (from the keyboard) and

//place it in the memory location named first_ value

cin >> first_value;

//Prompt the user to enter the second integer

cout << "Enter second integer" << endl;

//Read the second integer and place it in the memory location named second_value

cin >> second_value;

// Add first_value and second_value

// and store the result in sum_of_values.

sum_of_values = first_value + second_value;

// Display the phrase "first_integer = " and the value of the first integer.

cout << "first integer = " << first_value << endl;

// Display the phrase "second_integer = " and the value of the second integer.

cout << "second_integer = " << second_value << endl;

// Display the phrase " first integer + second integer = " and the sum of the two integers.

cout << " first integer + second integer = " << sum_of_values << endl;

// Our program returns a value of zero.

return 0;

}

References:

I have a Bachelor of Science degree in Electrical Engineering and worked as an embedded systems software engineer.

"The Complete Reference C++" Fourth edition ISBN 0-07-222680-3

My experience as an embedded systems software engineer designing and testing C++ applications.

How Your Conputer Uses Memory

I originally published this article on Yahoo Voices under the pen name John Mario.

Most new computer has several gigabytes of memory. A gigabyte is 1,000,000,000 bytes. This article talks about how your computer keep track of where everything is stored in this memory. You don't need a background in electronics to read this article. It is an article for those who want to learn about computer memory without getting buried in a myriad of complicated technical terms.

Let's digress for a moment. Each family that lives on any given street has a door number on their front door. That door number, as you well know, is part of your address.

Every memory location has an address associated with it. For purposes of this discussion, a memory location is defined as one byte of memory. A byte can hold an 8 digit binary number. In decimal, this means a byte can hold any number from 0 to 255.

When the computer program wants to write data to memory, it accesses memory via the memory address. As you learned in my article on programming, the programmer assigns a name to a memory location. The name describes what is in that memory location. That name is associated with a memory address. Lets assume the name is price_of_apple and the memory address is 36125. Now we write an instruction in our program to save the value 0.95 in the memory named price_of_apple. When that instruction is executed, the memory location with the address 16125 will contain the value 0.95. The English explanation would be that an apple costs $0.95.

Lets take a closer look at what is happening inside your computer without getting buried in mounds of technical jargon:

Basically there are two different types of memory: sequential access and random access. In sequential access memory, you must read everything that is in memory in the order that the data appears until you find the data you are looking for.

In random access memory, you can read any memory locations you want without having to read the other locations. This article will focus on random access memory.

A memory stick inside my HP computer looks like a thin rectangular piece of plastic with multiple pins on one edge. Inside my computer is an Intel computer chip. This Intel chip is referred to as a processor. When the computer program wants to store the price of an apple in memory, the processor sends that price, 0.95, to the memory stick. The processor also sends the address 36125 to the memory stick. Then the processor sends a command to the memory stick telling it to save the price at the memory address. Hence the price is written to the memory location whose address was sent by the processor.

Now let's talk about reading a memory location. When the computer program wants to read the price of an apple, the processor sends the address (36125) of the memory location price_of_apple to the memory stick. Then the processor commands the memory stick to send the price back to the processor. The memory stick sends the price (0.95) to the processor.

This concludes the explanation of how your computer uses memory.

References

I have a Bachelor of Science degree in Electrical Engineering and worked as an embedded systems software engineer.

A Generic Introduction To Computer Programming

I originally published this article on Yahoo Voices under the pen name John Mario.

This article does not focus on any particular computer language. It introduces computer programming by explaining some of the programming instructions that exist in all computer languages. It is directed toward those who are curious about computer programming, but have not yet decided to devote time and money to it.
 
Computer Programming is the art of using a set of instructions to force the computer to perform a certain task. The programming instructions described in this article will be written in plain english.
The following computer language instructions will be explained in this article:

The assignment statement
The PRINT instruction
The IF instruction
The ELSE instruction
The INPUT instruction
The WHILE instruction
The FOR loop
Instructions that perform math operations.

The Assignment statement
Any computer program needs to store temporary data provided by the programmer in memory. The programmer simply provides a name for the data being stored and the value of that data. The programmer does not have to know the exact memory location. The program automatically takes care of that.

For example: If you want to store the price of an apple, you could use the word apple_price as the name of the memory the price of apples is stored in. Then you store a price in the memory named apple_price. The instuction would look like this:

apple_price = 0.25

The statement simply states to store the value 0.25 in the memory named apple_price. This statement is known as an assignment statement. It assigns a value to the memory named apple_price.

The PRINT Instruction

The PRINT instruction can be used to display a value on the monitor. You can use the print instruction to display words, phrases and values.

Here is an instruction that displays the price of an apple.
print apple_price

Different languages will have different rules for typing the PRINT instruction. Some languages demand a set of parenthesis around the value to be printed.

print (apple_price)

You could also use the print statement to print a phrase. The instruction

print "Hello world!"

will display the message Hello world! on the monitor.

The IF Instruction

The IF instuction tells the computer when a specific action should be performed. For example, we want the computer to print the price of an apple if the price was less than one dollar:

If apple_price is less then 1.00, print apple_price.

The way to type less than is different for different languages.

The ELSE statement

The ELSE statement is part of the IF statement.
For example:

if apple-price is less than a quarter, then buy apples, else don't buy apples

The INPUT Instruction

The INPUT instruction tells the computer to read a value from a particular input. For purposes of this article, that input will be the keyboard. Not all programming languages name this instruction INPUT. The input instruction defines where it wants the input to be stored. For example

apple_price = input

tells the computer to input a value from the keyboard and store it in the memory named apple_price.

The WHILE Instruction

The while instruction commands the computer to keep doing something as long as specified condition exists. Here is a real life example of the WHILE instruction:

while tornado is near, stay in cellar

The FOR Instruction

The FOR instruction is used to repeat a something a specific number of times. The FOR instruction uses a counter to count the number of times the action is performed. Suppose we wanted to print apple_price five times. We would create a new memory name index to use as a counter.
For example

For index = 0 to 4, print apple_price

This instruction will set the value of index to 0 and prints the price of an apple, then it sets the value of index to 1 and prints the price of an apple. It increments the value of index and prints the price of an apple again. When the value of index is greater than 4, it stops printing the price of an apple. Hence, the price of an apple is printed five times: once for each value of index between 0 and 4.

Math
Math statements are also allowed in all programming languages. For example;

number_of_apples = 5
number_of_oranges = 3
total_number_of_fruit = number_of_apples + number_of_oranges

The memory named total will contain the sum of 5 and 3. Note that in this example, we wrote a short program containing three instructions. The first instruction sets the number_of_apples to 5. The second instruction sets the number_of_oranges to 3. The third instruction adds the number_of apples and the number_of_oranges to obtain the total_number_of_fruit. If we added an instruction to print the total_number_of_fruit, our program would look like this:

number_of_apples = 5
number_of_oranges = 3
total_number_of_fruit = number_of_apples + number_of_oranges
print total_number_of_fruit

References:

I have a Bachelor of Science degree in Electrical Engineering and I worked as an Embedded Systems Software Engineer. I designed and modified programs in several assembly languages and two high level languages.