Monday, September 29, 2008

Switch

The selective Structure: switch.

The syntax of the switch instruction is a bit peculiar. Its objective is to check several possible constant values for an expression, something similar to what we did at the beginning of this section with the linking of several if and else if sentences.  Its form is the following:
 switch (expression) {
  case constant1:
    block of instructions 1
    break;

case constant2:
    block of instructions 2

break;

 default:

 default block of instructions

  }



 
It works in the following way: switch evaluates expression and checks if it is equivalent to constant1, if it is, it executes block of instructions 1 until it finds the break keyword, then the program will jump to the end of the switch selective structure.



If expression was not equal to constant1 it will check if expression is equivalent to constant2. If it is, it will execute block of instructions 2 until it
finds the break keyword.



Finally, if the value of expression has not matched any of the previously specified constants (you may specify as many case sentences as values you want to check), the program will execute the instructions included in the default: section, if this one exists, since it is optional.
 

Both of the following code fragments are equivalent:

switch example

switch (x) {
  case 1:
    cout << "x is 1";
    break;
  case 2:
    cout << "x is 2";
    break;
  default:
    cout << "value of x unknown";
  }

if-else equivalent

if (x == 1)
{

cout << "x is 1";

}
else if (x == 2)
{

cout << "x is 2";

}

else
{

cout << "value of x unknown";

}

Source: cplusplus.com

Control Structure

A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose, C++ provides control structures that serve to specify what has to be done to perform our program.

With the introduction of control sequences we are going to have to introduce a new concept: the block of instructions. A block of instructions is a group of instructions separated by semicolons (;) but grouped in a block delimited by curly bracket signs: { and }.

Most of the control structures that we will see in this section allow a generic statement as a parameter, this refers to either a single instruction or a block of instructions, as we want. If we want the statement to be a single instruction we do not need to enclose it between curly-brackets ({}). If we want the statement to be more than a single instruction we must enclose them between curly brackets ({}) forming a block of instructions.

Conditional structure: if and else

It is used to execute an instruction or block of instructions only if a condition is fulfilled. Its form is:

if (condition) statement

where condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues on the next instruction after the conditional structure.

For example, the following code fragment prints out x is 100 only if the value stored in variable x is indeed 100:

if (x == 100)
cout << "x is 100";

If we want more than a single instruction to be executed in case that condition is true we can specify a block of instructions using curly brackets { }:

if (x == 100)
{
cout << "x is ";
cout << x;
}

We can additionally specify what we want that happens if the condition is not fulfilled by using the keyword else. Its form used in conjunction with if is:

if (condition) statement1 else statement2

For example:

if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";

prints out on the screen x is 100 if indeed x is worth 100, but if it is not -and only if not- it prints out x is not 100.

The if + else structures can be concatenated with the intention of verifying a range of values. The following example shows its use telling if the present value stored in x is positive, negative or none of the previous, that is to say, equal to zero.

if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";

Remember that in case we want more than a single instruction to be executed, we must group them in a block of instructions by using curly brackets { }.



Source : Cplusplus.com

Communication through console

The console is the basic interface of computers, normally it is the set composed of the keyboard and the screen. The keyboard is generally the standard input device and the screen the standard output device.

In the iostream C++ library, standard input and output operations for a program are supported by two data streams: cin for input and cout for output. Additionally, cerr and clog have also been implemented - these are two output streams specially designed to show error messages. They can be redirected to the standard output or to a log file.

Therefore cout (the standard output stream) is normally directed to the screen and cin (the standard input stream) is normally assigned to the keyboard.

By handling these two streams you will be able to interact with the user in your programs since you will be able to show messages on the screen and receive his/her input from the keyboard.

Output (cout)

The cout stream is used in conjunction with the overloaded operator << (a pair of "less than" signs).

cout << "Output sentence"; // prints Output sentence on screen
cout << 120;               // prints number 120 on screen
cout << x;                 // prints the content of variable x on screen

Input (cin).

Handling the standard input in C++ is done by applying the overloaded operator of extraction (>>) on the cin stream. This must be followed by the variable that will store the data that is going to be read. For example:

int age;
cin >> age;

Source : Cplusplus.com

Data Types

Here is the kind of Data types, able use in C++

  • Unsigned Char
  • Char
  • Enumeration
  • Unsigned Int
  • Short Int
  • Int
  • Unsigned Long
  • Long
  • Float
  • Double
  • Long Double

Declaration of variables

In order to use a variable in C++, we must first declare it specifying which of the data types above we want it to be. The syntax to declare a new variable is to write the data type specifier that we want (like int, short, float...) followed by a valid variable identifier. For example:

int a;
float mynumber;

Operator

Arithmetic operators ( +, -, *, /, % )

The five arithmetical operations supported by the language are:

+

addition

-

subtraction

*

multiplication

/

division

%

module

Compound assignation operators (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=) (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)

value += increase; is equivalent to value = value + increase;

a -= 5; is equivalent to a = a - 5;

a /= b; is equivalent to a = a / b;

price *= units + 1; is equivalent to price = price * (units + 1);

Example:

#include

void main()

{

int number;

clrscr();

number=10;

cout<<“Number before given any operator symbol: “<<number;

number+=5;

cout<<“\nThe result number +=5 : “<<number;

number-=10;

cout<<“\nThe result number -=10 : “<<number;

number*=10;

cout<<“\nThe result number *=10 : “<<number;

getch();

}

If above program is execution will appear result that shown in below:

Number before given any operator symbol: 10

The result number +=5 : 15

The result number -=10 : 5

The result number *=10 : 50

Relational operators ( ==, !=, >>, <, >=, <= )

In order to evaluate a comparison between two expressions we can use the Relational operators. As specified by the ANSI-C++ standard, the result of a relational operation is a Boolean value that can only be true or false, according to the result of the comparison.

We may want to compare two expressions, for example, to know if they are equal or if one is greater than the other. Here is a list of the relational operators that can be performed in C++:

== Equal

!= Different

&gt; Greater than

< Less than

<= Greater or equal than

>= Less or equal than

Example:

(7 == 5) would return false.

(5 > 4) would return true.

Logic operators ( !, &&&, || ).

The Operator of ! is equivalent to boolean operation NOT, it has only one operand, located at its right, and the only thing that it does is to invert the value of it, producing false if its operand is true and true if its operand is false. It is like saying that it returns the opposite result of evaluating its operand. For example:

!(5 == 5) returns false

Logic operators && and || are used when evaluating two expressions to obtain a single result. They correspond with boolean logic operations AND and OR respectively. The result of them depends on the relation between its two operands:

A

B

A && B

A || B

True

True

True

True

True

False

False

True

False

True

False

True

False

False

False

False


Source: cplusplus.com



Introduction to C++ -cont-

Escape Code

Escape codes are special characters that cannot be expressed otherwise in the source code of a program, like newline (\n) or tab (\t). All of them are preceded by an inverted slash (\). Here you have a list of such escape codes:

\n

newline

\r

carriage return

\t

tabulation

\v

vertical tabulation

\b

backspace

\f

page feed

\a

alert (beep)

\'

single quotes (')

\"

double quotes (")

\?

question (?)

\\

inverted slash (\)


Variable

We can define a variable as a portion of memory to store a determined value, and the value could change since the program is executed. Variable could consist of letter, numeric and underline symbol (_). Least they are three points we have to do in writing variable:

- Have to begin with letter

- Without space

- Cannot match with any key word in C++ language

For example, the following expressions are always considered key words according to the ANSI-C++ standard and therefore they must not be used as identifiers:

asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t

Very important: The C++ language is "case sensitive", that means that an identifier written in capital letters is not equivalent to another one with the same name but written in small letters. Thus, for example the variable RESULT is not the same as the variable result nor the variable Result.

Constants

A constant is any expression that has a fixed value. They can be divided in Integer Numbers, Floating-Point Numbers, Characters and Strings



Source : Cplusplus.com

Introduction to C++

Structure of a C++ Program

Structure of a C++ program is shown as a collection from one or more function.

Example:

#include

void main()

{

Statement1

Statement2

Statement3

}

File header declaration based on the statement we are used. Following a simple program in C++:

#include

void main()

{

clrscr();

cout<<”Hello World”;

getch();

}

We are going to look them one by one:

#include

Sentences that begin with a pound sign (#) are directives for the preprocessor. They are not executable code lines but indications for the compiler. In this case the sentence #include tells the compiler's preprocessor to include the iostream standard header file. This specific file includes the declarations of the basic standard input-output library in C++, and it is included because its functionality is used later in the program.

void main ()

This line corresponds to the beginning of the main function declaration. The main function is the point where all C++ programs begin their execution. It is independent of whether it is at the beginning, at the end or in the middle of the code - its content is always the first to be executed when a program starts. In addition, for that same reason, it is essential that all C++ programs have a main function.

main is followed by a pair of parenthesis () because it is a function. In C++ all functions are followed by a pair of parenthesis () that, optionally, can include arguments within them. The content of the main function immediately follows its formal declaration and it is enclosed between curly brackets ({}), as in our example.

cout << "Hello World";

This instruction does the most important thing in this program. cout is the standard output stream in C++ (usually the screen), and the full sentence inserts a sequence of characters (in this case "Hello World") into this output stream (the screen). cout is declared in the iostream.h header file, so in order to be able to use it that file must be included.

Notice that the sentence ends with a semicolon character (;). This character signifies the end of the instruction and must be included after every instruction in any C++ program (one of the most common errors of C++ programmers is indeed to forget to include a semicolon ; at the end of each instruction).

Comments

Comments are pieces of source code discarded from the code by the compiler. They do nothing. Their purpose is only to allow the programmer to insert notes or descriptions embedded within the source code.

C++ supports two ways to insert comments:

// line comment
/* block comment */



Source : Cplusplus.com

Basic Programming Case

Introduction to real programming
The real case in programming always very complex and have relation with any procedure. Even though, to practice our programming logic and algorithm to solve the complex case, we use a simple case but needs a high logic. The following cases are: progression/sequence, validation, positioning and string manipulation.

Progression/Sequence
A number sequence is one of algorithm that always used to practice programming logic. In simple form, the exercise of sequence just print out a sequence numbers. For example:
– 1,3,5,7,9,…
– 2,7,12,17,22,…


Validation & Verification
Validation is a process to check the input with some exact criteria. Validation is the most important algorithm with GIGO (Garbage In Garbage Out) principle, it means the wrong input will result the wrong output too.
• Example:
– The name are consists of letter only.
– Address, email couldn’t consist with following signs @,#,%,$, and others.

Verification check the right input have been through needs or not.
For example of Input is: Address that shown on following: Jl. Nonsen No.123
• Input Valid (consists of letters, number and dot)
• Verification; check if Jl. Nonsen is available and no 123 is available too.

Positioning & Animation
Positioning is a process in making a various form in the screen with basic character like *, but could be shown as other form with position setting.



The Positioning is a basic of create animation. With change a position in each time, it makes the character like move around.

String manipulation
The String manipulation is a capability to set a form of data in order to make it suitable with the data requirement.