PLC – Chapter 6 – Control Structures Statement

A control structure is a control statement and the collection of statements whose execution it controls.

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 by our program, when and under which circumstances.

With the introduction of control structures we are going to have to introduce a new concept: the compound-statement or block. A block is a group of statements which are separated by semicolons (;) like all C++ statements, but grouped together in a block enclosed in braces “{ }”

{ statement1; statement2; statement3; }

Most of the control structures require a generic statement as part of its syntax. A statement can be either a simple statement which is a simple instruction ending with a semicolon or a compound statement which is several instructions grouped in a block, like the one just described. In the case that a simple statement, it does not need to enclose it in braces ({}). But in the case of a compound statements , it must be enclosed between braces ({}), forming a block.

 

  1. Selection Statements
  2. Two-Way Selection Statements

The if keyword is used to execute a statement or block 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 right after this conditional structure.

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

1
2
if (x == 100)

cout << “x is 100”;

If we want more than a single statement to be executed in case that the condition is true we can specify a block using braces { }:

1
2
3
4
5
if (x == 100)

{

cout << “x is “;

cout << x;

}

We can additionally specify what we want to happen 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:

1
2
3
4
if (x == 100)

cout << “x is 100”;

else

cout << “x is not 100”;

prints on the screen x is 100 if indeed x has a value of 100, but if it has 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 value currently stored in x is positive, negative or none of them (i.e. zero):

 

1
2
3
4
5
6
if (x > 0)

cout << “x is positive”;

else if (x < 0)

cout << “x is negative”;

else

cout << “x is 0”;

Remember that in case that we want more than a single statement to be executed, we must group them in a block by enclosing them in braces { }.

 

  1. Nesting Selection Statements

 

if( boolean_expression 1) {

// Executes when the boolean expression 1 is true

if(boolean_expression 2) {

// Executes when the boolean expression 2 is true

}

}

 

Nested if-else statements mean that you can use one if or else if statement inside another if or else if statements.

 

#include <iostream>

using namespace std;

 

int main () {

// local variable declaration:

int a = 100;

int b = 200;

 

// check the boolean condition

if( a == 100 ) {

// if condition is true then check the following

if( b == 200 ) {

// if condition is true then print the following

cout << “Value of a is 100 and b is 200” << endl;

}

}

 

cout << “Exact value of a is : ” << a << endl;

cout << “Exact value of b is : ” << b << endl;

 

return 0;

}

When the above code is compiled and executed, it produces the following result:

Value of a is 100 and b is 200

Exact value of a is : 100

Exact value of b is : 200

 

  1. Multiple-Way Selection Statements

Multiple-Way Selection Statements 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 concatenation of several if and else if instructions. Its form is the following:

 

switch (expression)

{

case constant1:

group of statements 1;

break;

case constant2:

group of statements 2;

break;

default:

default group of statements

}

It works in the following way: switch evaluates expression and checks if it is equivalent to constant1, if it is, it executes group of statements 1 until it finds the break statement. When it finds this break statement the program jumps to the end of the switch selective structure.

If expression was not equal to constant1 it will be checked against constant2. If it is equal to this, it will execute group of statements 2 until a break keyword is found, and then will jump to the end of the switch selective structure.

Finally, if the value of expression did not match any of the previously specified constants (you can include as many case labels as values you want to check), the program will execute the statements included after the default: label, if it exists (since it is optional).

Both of the following code fragments have the same behavior:

switch example if-else equivalent
switch (x) {

case 1:

cout << “x is 1”;

break;

case 2:

cout << “x is 2”;

break;

default:

cout << “value of x unknown”;

}

 

if (x == 1) {

cout << “x is 1”;

}

else if (x == 2) {

cout << “x is 2”;

}

else {

cout << “value of x unknown”;

}

 

The switch statement is a bit peculiar within the C++ language because it uses labels instead of blocks. This forces us to put break statements after the group of statements that we want to be executed for a specific condition. Otherwise the remainder statements -including those corresponding to other labels- will also be executed until the end of the switchselective block or a break statement is reached.

 

For example, if we did not include a break statement after the first group for case one, the program will not automatically jump to the end of the switch selective block and it would continue executing the rest of statements until it reaches either a break instruction or the end of the switch selective block. This makes it unnecessary to include braces { }surrounding the statements for each of the cases, and it can also

be useful to execute the same block of instructions for different possible values for the expression being evaluated. For example:

 

1
2
3
4
5
6
7
8
9
switch (x) {

case 1:

case 2:

case 3:

cout << “x is 1, 2 or 3”;

break;

default:

cout << “x is not 1, 2 nor 3”;

}

Notice that switch can only be used to compare an expression against constants. Therefore we cannot put variables as labels (for example case n: where n is a variable) or ranges (case (1..3):) because they are not valid C++ constants.

 

If you need to check ranges or values that are not constants, use a concatenation of if and else if statements.

 

  1. Iteration Statements

An iterative statement is one that causes a statement or collection of statements to be executed zero, one, or more times. An iterative statement is often called a loop. Iteration is the very essence of the power of the computer. If some means of repetitive execution of a statement or collection of statements were not possible, programmers would be required to state every action in sequence; useful programs would be huge and inflexible and take unacceptably large amounts of time to write and mammoth amounts of memory to store.

 

  1. Counter-Controlled Loops

A counting iterative control statement has a variable, called the loop variable, in which the count value is maintained. It also includes some means of specifying the initial and terminal values of the loop variable, and the difference between sequential loop variable values, often called the stepsize. The initial, terminal, and stepsize specifications of a loop are called the loop parameters.

Its format is: for (initialization; condition; increase) statement;

and its main function is to repeat statement while condition remains true, like the while loop. But in addition, the for loop provides specific locations to contain an initialization statement and an increase statement. So this loop is specially designed to perform a repetitive action with a counter which is initialized and increased on each iteration.

It works in the following way:

  1. initialization is executed. Generally, it is an initial value setting for a counter variable. This is executed only once.
  2. condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped (not executed).
  3. statement is executed. As usual, it can be either a single statement or a block enclosed in braces { }.
  4. finally, whatever is specified in the increase field is executed and the loop gets back to step 2.
  5. Here is an example of countdown using a for loop:
1
2
3
4
5
6
7
8
9
10
11
// countdown using a for loop

#include <iostream>

using namespace std;

int main ()

{

for (int n=10; n>0; n–) {

cout << n << “, “;

}

cout << “FIRE!\n”;

return 0;

}

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

The initialization and increase fields are optional. They can remain empty, but in all cases the semicolon signs between them must be written. For example we could write: for (;n<10;) if we wanted to specify no initialization and no increase; or for (;n<10;n++) if we wanted to include an increase field but no initialization (maybe because the variable was already initialized before).

Optionally, using the comma operator (,) we can specify more than one expression in any of the fields included in a forloop, like in initialization, for example. The comma operator (,) is an expression separator, it serves to separate more than one expression where only one is generally expected. For example, suppose that we wanted to initialize more than one variable in our loop:

1
2
3
4
for ( n=0, i=100 ; n!=i ; n++, i– )

{

// whatever here…

}

This loop will execute for 50 times if neither n or i are modified within the loop:
n starts with a value of 0, and i with 100, the condition is n! = i (that n is not equal to i). Because n is increased by one and i decreased by one, the loop’s condition will become false after the 50th loop, when both n and i will be equal to 50.

  1. Logically Controlled Loops

Logically controlled loops are more general than counter-controlled loops. Every counting loop can be built with a logical loop, but the reverse is not true. Also, recall that only selection and logical loops are essential to express the control structure of any flowchart.

 

 

Pre-test Loop

In the pretest version of a logical loop (while), the statement or statement segment is executed as long as the expression evaluates to true.

Its format is: while (expression) statement

and its functionality is simply to repeat statement while the condition set in expression is true.

 

 

For example, we are going to make a program to countdown using a while-loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// custom countdown using while

#include <iostream>

using namespace std;

 

int main ()

{

int n;

cout << “Enter the starting number > “;

cin >> n;

 

while (n>0) {

cout << n << “, “;

–n;

}

 

cout << “FIRE!\n”;

return 0;

}

Enter the starting number > 8

8, 7, 6, 5, 4, 3, 2, 1, FIRE!

When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop begins, if the value entered by the user fulfills the condition n>0 (that n is greater than zero) the block that follows the condition will be executed and repeated while the condition (n>0) remains being true.

The whole process of the previous program can be interpreted according to the following script (beginning in main):

  1. User assigns a value to n
  2. The while condition is checked (n>0). At this point there are two possibilities:
    * condition is true: statement is executed (to step 3)
    * condition is false: ignore statement and continue after it (to step 5)
  3. Execute statement:
    cout << n << “, “;
    –n;
    (prints the value of n on the screen and decreases n by 1)
  4. End of block. Return automatically to step 2
  5. Continue the program right after the block: print FIRE! and end program.

When creating a while-loop, we must always consider that it has to end at some point, therefore we must provide within the block some method to force the condition to become false at some point, otherwise the loop will continue looping forever. In this case we have included –n; that decreases the value of the variable that is being evaluated in the condition (n) by one – this will eventually make the condition (n>0) to become false after a certain number of loop iterations: to be more specific, when n becomes 0, that is where our while-loop and our countdown end.

Of course this is such a simple action for our computer that the whole countdown is performed instantly without any practical delay between numbers.
 

Post-Test Loop

In the posttest loop (do), the loop body is executed until the expression evaluates to false. The only real difference between the do and the while is that the do always causes the loop body to be executed at least once.

Its format is: do statement while (condition);

Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. For example, the following example program echoes any number you enter until you enter 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// number echoer

 

#include <iostream>

using namespace std;

 

int main ()

{

unsigned long n;

do {

cout << “Enter number (0 to end): “;

cin >> n;

cout << “You entered: ” << n << “\n”;

} while (n != 0);

return 0;

}

Enter number (0 to end): 12345

You entered: 12345

Enter number (0 to end): 160277

You entered: 160277

Enter number (0 to end): 0

You entered: 0

The do-while loop is usually used when the condition that has to determine the end of the loop is determined within the loop statement itself, like in the previous case, where the user input within the block is what is used to determine if the loop has to end. In fact, if you never enter the value 0 in the previous example you can be prompted for more numbers forever.

 

  1. User-Located Loop Control Mechanisms

The break statement

Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite loop, or to force it to end before its natural end. For example, we are going to stop the count down before its natural end

 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// break loop example

 

#include <iostream>

using namespace std;

 

int main ()

{

int n;

for (n=10; n>0; n–)

{

cout << n << “, “;

if (n==3)

{

cout << “countdown aborted!”;

break;

}

}

return 0;

}

10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!

 

The continue statement

The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to jump to the start of the following iteration. For example, we are going to skip the number 5 in our countdown:

1
2
3
4
5
6
7
8
9
10
11
12
13
// continue loop example

#include <iostream>

using namespace std;

 

int main ()

{

for (int n=10; n>0; n–) {

if (n==5) continue;

cout << n << “, “;

}

cout << “FIRE!\n”;

return 0;

}

10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!

 

The go to statement

goto allows to make an absolute jump to another point in the program. You should use this feature with caution since its execution causes an unconditional jump ignoring any type of nesting limitations.

The destination point is identified by a label, which is then used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:).

Generally speaking, this instruction has no concrete use in structured or object oriented programming aside from those that low-level programming fans may find for it.

 

For example, here is our countdown loop using goto:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// goto loop example

 

#include <iostream>

using namespace std;

 

int main ()

{

int n=10;

loop:

cout << n << “, “;

n–;

if (n>0) goto loop;

cout << “FIRE!\n”;

return 0;

}

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

The exit function

exit is a function defined in the cstdlib library. The purpose of exit is to terminate the current program with a specific exit code. Its prototype is:

void exit (int exitcode);

The exitcode is used by some operating systems and may be used by calling programs. By convention, an exit code of 0means that the program finished normally and any other value means that some error or unexpected results happened.

 

  1. Iteration Based on Data Structure

A general data-based iteration statement uses a user-defined data structure and a user-defined function (the iterator) to go through the structure’s elements. The iterator is called at the beginning of each iteration, and each time it is called, the iterator returns an element from a particular data structure in some specific order. For example, suppose a program has a user-defined binary tree of data nodes, and the data in each node must be processed in some particular order. A user-defined iteration statement for the tree would successively set the loop variable to point to the nodes in the tree, one for each iteration. The initial execution of the user-defined iteration statement needs to issue a special call to the iterator to get the first tree element. The iterator must always remember which node it presented last so that it visits all nodes without visiting any node more than once. So, an iterator must be history sensitive. A user-defined iteration statement terminates when the iterator fails to find more elements.

 

 

 

 

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • Twitter
  • RSS

PLC – Chapter 5 – Expression and Assignment Statements

Expression Statements

A combination of variables, constants and operators that represents a computation forms an expression. Depending upon the type of operands involved in an expression or the result obtained after evaluating expression, there are different categories of an expression. These categories of an expression are discussed here.

  • Constant expressions: The expressions that comprise only constant values are called constant expressions. Some examples of constant expressions are 20, ‘ a‘ and 2/5+30 .
  • Integral expressions:The expressions that produce an integer value as output after performing all types of conversions are called integral expressions. For example, x, 6*x-y and 10 +int (5.0) are integral expressions. Here, x and yare variables of type into.
  • Float expressions:The expressions that produce floating-point value as output after performing all types of conversions are called float expressions. For example, 9.25, x-y and 9+ float (7) are float expressions. Here, x ‘and yare variables of type float.
  • Relational or Boolean expressions:The expressions that produce a bool type value, that is, either true or false are called relational or Boolean expressions. For example, x + y<100, m + n==a-b and a>=b + c .are relational expressions.
  • Logical expressions:The expressions that produce a bool type value after combining two or more relational expressions are called logical expressions. For example, x==5 &&m==5 and y>x I I m<=n are logical expressions.
  • Bitwise expressions:The expressions which manipulate data at bit level are called bitwise expressions. For example, a >> 4 and b<< 2 are bitwise expressions.
  • Pointer expressions:The expressions that give address values as output are called pointer  For example, &x, ptr and -ptr are pointer expressions. Here, x is a variable of any type and ptr is a pointer.
  • Special assignment expressions:An expression can be categorized further depending upon the way the values are assigned to the variables.
  • Chained assignment: Chained assignmentis an assignment expression in which the same value is assigned to more than one variable, using a single statement. For example, consider these statements.

a = (b=20); or a=b=20;

In these statements, value 20 is assigned to variable b and then to variable a. Note that variables cannot be initialized at the time of declaration using chained assignment. For example, consider these statements.

int a=b=30; // illegal

int a=30, int b=30; //valid

  • Embedded assignment: Embedded assignment is an assignment expression, which is enclosed within another assignment expression. For example, consider this statement

a=20+(b=30);   //equivalent to b=30; a=20+30;

In this statement, the value 30 is assigned to variable b and then the result of (20+ 30) that is, 50 is assigned to variable a. Note that the expression (b=30) is an embedded assignment.

  • Compound Assignment: Compound Assignmentis an assignment expression, which uses a compound assignment operator that is a combination of the assignment operator with a binary arithmetic operator. For example, consider this statement.

a + =20; //equivalent to a=a+20;

In this statement, the operator += is a compound assignment operator, also known as short-hand assignment operator.

Type Conversion

An expression· may involve variables and constants either of same data type or of different data types. However, when an expression consists of mixed data types then they are converted to the same type while evaluation, to avoid compatibility issues. This is accomplished by type conversion, which is defined as the process of converting one predefined data type into another. Type conversions are of two types, namely, implicit conversions and explicit conversions also known as typecasting.

  • Implicit Conversions

Implicit conversion, also known as automatic type conversion refers to the type conversion that is automatically performed by the compiler. Whenever compiler confronts a mixed type expression, first of all char and short int values are converted to int. This conversion is known as integral promotion. After applying this conversion, all the other operands are converted to the type of the largest operand and the result is of the type of the largest operand. Table 3.8 illustrates the implicit conversion of data type starting from the smallest to largest data type. For example, in expression 5 + 4.25, the compiler converts the int into float as float is larger than int and then performs the addition.

1

Typecasting refers to the type conversion that is performed explicitly using type cast operator. In C++, typecasting can be performed by using two different forms which are given here.

data_type (expression) //expression in parentheses

                                   (data_type)expression //data type in parentheses

where,

data_type = data type (also known as cast operator) to which the expression is to be converted.

To understand typecasting, consider this example.

                                    float (num)+ 3.5; //num is of int type

In this example, float () acts as a conversion function which converts int to float. However, this form of conversion cannot be used in some situations. For example, consider this statement.

ptr=int * (x) ;

In such cases, conversion can be done using the second form of typecasting (which is basically C-style typecasting) as shown here.

                                           ptr=(int*)x;

 

Assignment Statement in C++

It is essential that every variable in a program is given a value explicitly before any attempt is made to use it. It is also very important that the value assigned is of the correct type.The most common form of statement in a program uses the assignment operator, =, and either an expression or a constant to assign a value to a variable:

                                 variable = expression;
                                 variable = constant;

The symbol of the assignment operator looks like the mathematical equality operator but in C++ its meaning is different. The assignment statement indicates that the value given by the expression on the right hand side of the assignment operator (symbol =) must be stored in the variable named on the left hand side. The assignment operator should be read as “becomes equal to” and means that the variable on the left hand side has its value changed to the value of the expression on the right hand side. For the assignment to work successfully, the type of the variable on the left hand side should be the same as the type returned by the expression.

The statement in line 10 of the simple adder program is an example of an assignment statement involving an arithmetic expression.

total = a + b;

It takes the values of a and b, sums them together and assigns the result to the variable total. As discussed above, variables can be thought of as named boxes into which values can be stored. Whenever the name of a box (i.e. a variable) appears in an expression, it represents the value currently stored in that box. When an assignment statement is executed, a new value is dropped into the box, replacing the old one. Thus, line 10 of the program means “get the value stored in the box named a, add it to the value stored in the box named b and store the result in the box named total”.

The assignment statement:

total = total + 5;

is thus a valid statement since the new value of total becomes the old value of total with 5 added to it. Remember the assignment operator (=) is not the same as the equality operator in mathematics (represented in C++ by the operator ==).

 

Arithmetic expressions

Expressions can be constructed out of variables, constants, operators and brackets. The commonly used mathematical or arithmetic operators include:

Operator Operation
+ addition
subtraction
* multiplication
/ division
% modulus (modulo division)

The definitions of the first four operators are as expected. The modulo division (modulus) operation with an integer is the remainder after division, e.g. 13 modulus 4 (13%4) gives the result 1. Obviously it makes no sense at all to use this operator with float variables and the compiler will issue a warning message if you attempt to do so.

Although addition, subtraction and multiplication are the same for both integers and reals (floating point numbers), division is different. If you write (see later for declaration and initialisation of variables on the same line):

float a=13.0, b=4.0, result;

result = a/b;

Then a real division is performed and 3.25 is assigned to result. A different result would have been obtained if the variables had been defined as integers:

int i=13,j=4, result;

result = i/j;

when result is assigned the integer value 3.

The remainder after integer division can be determined by the modulo division (modulus) operator, %. For example, the value of i%j would be 1.

 

Precedence and nesting parentheses

The use of parentheses (brackets) is advisable to ensure the correct evaluation of complex expressions. Here are some examples:

4+2*3 equals 10
(4+2)*3 equals 18
-3 * 4 equals -12
4 * -3 equals -12 (but should be avoided)
4 * (-3) equals -12
0.5 (a+b) illegal (missing multiplication operator)
(a+b) / 2 equals the average value of a and b only if they are of type float

The order of execution of mathematical operations is governed by rules of precedence. These are similar to those of algebraic expressions. Parentheses are always evaluated first, followed by multiplication, division and modulus operations. Addition and subtraction are last. The best thing, however, is to use parentheses (brackets) instead of trying to remember the rules.

 

Initialisation of variables

Variables can be assigned values when they are first defined (called initialisation):

type variable = literal constant;
float ratio = 0.8660254;
int myAge = 19;
char answer = ‘y’;
bool raining = false;

The terms on the right hand side are called constants.

(Note the ASCII character set is represented by type char. Each character constant is specified by enclosing it between single quotes (to distinguish it from a variable name). Each char variable can only be assigned a single character. These are stored as numeric codes. The initialisation of words and character strings will be discussed later in the section on advanced topics.)

The declaration of a variable and the assignment of its value in the same statement can be used to define variables as they are needed in the program.

 type     variable = expression;
float   product = factor1*factor2;

The variables in the expression on the right hand side must of course have already been declared and had values assigned to them.

Warning: When declaring and initialising variables in the middle of a program, the variable exists (i.e. memory is assigned to store values of the variable) up to the first right brace that is encountered, excluding any intermediate nested braces, { }. For the simple programs described here, this will usually be the closing brace mark of the program. However we will see later that brace marks can be introduced in many parts of the program to make compound statements.

 

Expressions with mixed variable types

At a low level, a computer is not able to perform an arithmetic operation on two different data types of data. In general, only variables and constants of the sametype, should be combined in an expression. The compiler has strict type checking rules to check for this.

In cases where mixed numeric types appear in an expression, the compiler replaces all variables with copies of the highest precision type. It promotes them so that in an expression with integers and float variables, the integer is automatically converted to the equivalent floating point number for the purpose of the calculation only. The value of the integer is not changed in memory. Hence, the following is legal:

int i=13;

float x=1.5;

x = (x * i) + 23;

since the values of i and 23 are automatically converted to floating point numbers and the result is assigned to the float variable x.

However the expression:

int i=13,j=4;

float result;

result = i/j;

is evaluated by integer division and therefore produces the incorrect assignment of 3.0 for the value of result. You should try and avoid expressions of this type but occasionally you will need to compute a fraction from integer numbers. In these cases the compiler needs to be told specifically to convert the variables on the right-hand side of the assignment operator to type float. This is done by casting.

In the C++ language this is done by using the construction: static_cast< type > expression (In the C language this is done by a different construction using: (type) expression.)

For example:

int count=3, N=100;

float fraction;

fraction  = static_cast<float>(count)/N;

converts (casts) the value stored in the integer variable count into a floating point number, 3.0. The integer N is then promoted into a floating point number to give a floating point result.

Declaration and initialisation of symbolic constants

Like variables, symbolic constants have types and names. A constant is declared and initialised in a similar way to variables but with a specific instruction to the compiler that the value cannot be changed by the program. The values of constants must always be assigned when they are created.

const   type      constant-name = literal constant;

const   float    Pi = 3.14159265;

const   int      MAX = 10000;

The use of constants helps programmers avoid inadvertent alterations of information that should never be changed. The use of appropriate constant names instead of using the numbers also helps to make programs more readable.

 

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • Twitter
  • RSS

PLC – Chapter 4 – Data Types

Data types in any of the language means that what are the various type of data the variables can have in that particular language. Information is stored in a computer memory with different data types. Whenever a variable is declared it becomes necessary to define data type that what will be the type of data that variable can hold.

5

There are two data types available in C++:

  1. Primary Data Type character, integer, floating point, boolean, double floating point, void, wide character.
  2. Additional Data Types typedef, enumerated.

Character Data Types

Data Type (Keywords) Description Size Typical Range
char Any single character. It may include a letter, a digit, a punctuation mark, or a space. 1 byte -128 to 127 or 0 to 255
signed char Signed character. 1 byte -128 to 127
unsigned char Unsigned character. 1 byte 0 to 255
wchar_t Wide character. 2 or 4 bytes 1 wide character

 

Integer Data Types

Data Type (Keywords) Description Size Typical Range
int Integer. 4 bytes -2147483648 to 2147483647
signed int Signed integer. Values may be negative, positive, or zero. 4 bytes -2147483648 to 2147483647
unsigned int Unsigned integer. Values are always positive or zero. Never negative. 4 bytes 0 to 4294967295
short Short integer. 2 bytes -32768 to 32767
signed short Signed short integer. Values may be negative, positive, or zero. 2 bytes -32768 to 32767
unsigned short Unsigned short integer. Values are always positive or zero. Never negative. 2 bytes 0 to 65535
long Long integer. 4 bytes -2147483648 to 2147483647
signed long Signed long integer. Values may be negative, positive, or zero. 4 bytes -2147483648 to 2147483647
unsigned long Unsigned long integer. Values are always positive or zero. Never negative. 4 bytes 0 to 4294967295

Floating-point Data Types

Data Type (Keywords) Description Size Typical Range
float Floating point number. There is no fixed number of digits before or after the decimal point. 4 bytes +/- 3.4e +/- 38 (~7 digits)
double Double precision floating point number. More accurate compared to float. 8 bytes +/- 1.7e +/- 308 (~15 digits)
long double Long double precision floating point number. 8 bytes +/- 1.7e +/- 308 (~15 digits)

 

 

Boolean Data Type

Data Type (Keywords) Description Size Typical Range
bool Boolean value. It can only take one of two values: true or false. 1 byte true or false

Note: Variables sizes might be different in your pc from those shown in the above table, depending on the compiler you are using.

Below example will produce correct size of various data type, on your computer.

Example:

#include <iostream>

using namespace std;

 

int main()

{

cout << “Size of char is ” << sizeof(char) << endl;

cout << “Size of int is ” << sizeof(int) << endl;

cout << “Size of float is ” << sizeof(float) << endl;

cout << “Size of short int is ” << sizeof(short int) << endl;

cout << “Size of long int is ” << sizeof(long int) << endl;

cout << “Size of double is ” << sizeof(double) << endl;

cout << “Size of wchar_t is ” << sizeof(wchar_t) << endl;

return 0;

}

 

 

 

Program Output:

Size of char is 1

Size of int is 4

Size of float is 4

Size of short int is 2

Size of long int is 4

Size of double is 8

Size of wchar_t is 4

 

Enum Data Type

This is an user defined data type having finite set of enumeration constants. The keyword ‘enum‘ is used to create enumerated data type.

Syntax:

enum enum-name {list of names}var-list;

enum mca(software, internet, seo);

 

Typedef

It is used to create new data type. But it is commonly used to change existing data type with another name.

Syntax:

typedef [data_type] synonym;

or

typedef [data_type] new_data_type;

 

Example:

typedef int integer;

integer rollno;

 

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • Twitter
  • RSS

PLC – Chapter 3 – Names, Binding, Scopes

Naming Convention

There are various things that have to be paid attention to when giving name for a variable, class, and such in C++, such as the following:

  • Naming should be unique and a variable should not have the same name with other variables in the same scope.
  • Reserved words and keywords may not be used for a variable name.
  • Naming can only consist of alphabets (A-Z, a-z), numbers (-0-9), dollar symbol ($), and underscore (_).
  • The first character of the name should be either an alphabet or an underscore.
  • Names in C++ are case-sensitive, so, for example, the variable index and Index are different from each other. This may cause a problem in both readibility and writability as it considers similar names as different.
  • While there are no limit in character length, during execution the program will only recognize the first 32 characters of the name.
  • It is advised to use relevant, short, and clear names for variables, classes, etc., so when the coder or other people read the codes again, they would not be confused of what are the use of several variables and the variables would be easier to use.

Pay attention to the following snippet of codes:

int main() {

int 2nama, nim, _alamat, for;

cin>> 2nama >> NIM >> _alamat >> for;

}

There are a few mistakes that can be seen from the codes above:

  • During the declaration (line 1), the variable 2nama violated the rule that a name can only be started with alphabets or underscore, not numbers. The variable for can’t be used too, as for is already a keyword used for looping function.
  • During the value input of the variables (line 2), same as line 1, variables 2nama and for violate the rule. In addition, athe variable NIM would cause an error too as the compiler does not recognize that name, because C++ is a case-sensitive language, so it considers the variable nim declared on the first line different from the variable NIM used on the second line.Binding

Binding is the association between an entity and an attribute, such as the association of a variable and its attributes like name, address, data type, value, lifetime, and scope. Binding time is the time at which binding takes place.

The examples of binding time:

  • Language design time
  • Language implementation time
  • Program translation / compile time
  • Link edit time
  • Load time
  • Run time

For a variable to be able to be referenced in a program, first it need to be bound to a type, which is called type binding. It can be differentiated into two kinds of type binding:

  • Static type binding, binding that took place during compile time. The data type that the variable is bound to is decided either by directly specifying a data type to the variable name (explicit) or by default associating a variable with a type during compile time (implicit). In C++, Explicit static type binding is usually used.
  • Dynamic type binding, where a variable is bound to a type when it is assigned a value in an assignment statement (at run time, take the type of the value on the right-hand side). By using dynamic type binding, it’s more flexible compared to static type binding, but error detection is harder and prone to typing errors. In C++, dynamic type binding can be used with the help of template by using generics.

Scope

The scope of a variable is the range of statements over which it is visible. The scope rules of a language determine how references to names are associated with variables. In C++, the scope of a variable depends on the block where the variable is declared or called. There are two kinds of scope, static and dynamic scope.

Depending on the scope it is in, a variable can be divided into two kinds:

  • Local Variable is variable declared in a block of program and can only be called in said block.
  • Global Variable is variable declared outside of all block of programs and can be called from anywhere after its declaration. In the case when a global variable and a local variable share a name, the local variable will be prioritized if the variable name is called inside the same block of that local variable.
  • Static Scope

Static scope is based on program text and connect a name reference to a variable by finding the declaration. The search process of the declaration starts locally, then in increasingly larger enclosing scopes, until one is found for given name.

  • Dynamic Scope

Dynamic scope is based on calling sequences of program units, not their textual layout. References to variables are connected to declarations by searching back through the chain of subprogram calls that forced execution to this point.

 

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • Twitter
  • RSS

PLC – Chapter 2 – Describing Syntax and Semantics

Definition

The word syntax comes from Ancient Greek: σύνταξις “coordination”, which consists of σύν syn, “together,” and τάξις táxis, “an ordering”.

In computer science, the syntax of a computer language is the set of grammatical rules that defines the combinations of words and symbols that are considered to be a correctly structured document or fragment in that language.

Semantic focuses on the relationship between signifiers—like words, phrases, signs, and symbols—and what they stand for, their denotation. In computer science, semantics is the meaning of the expressions,  statements, and program units

C++ Syntax

The syntax of textual programming languages is usually defined using a combination of regular expressions (for lexical structure) and Backus–Naur Form (for grammatical structure) to inductively specify syntactic categories (nonterminals) and terminal symbols. Syntactic categories are defined by rules called productions, which specify the values that belong to a particular syntactic category. Terminal symbols are the concrete characters or strings of characters (for example keywords such as defineifmain, or void) from which syntactically valid programs are constructed.

The following are the examples of basic C++ keywords syntax:

  1. #include, which is used to insert the library of functions we are going to use in our program. For example, #include <iostream>, which includes the standard input and output codes.
  2. int main(), which is called first by the program after the initialization. A statement return 0; should be written at the end of the codes inside int main().
  3. cout, which is used to print output on the screen.
  4. cin, which is used to input data by user and store it as a variable.
  5. int, char, etc., which are used to declare a variable, according to the data types. (int for integer, char for a character, string for string of characters, etc.)
  6. if, which is used in selection and will execute the codes if the condition is true.
  7. while, for, are used in looping/reiteration.

There are also various points that should be paid attention to:

  1. The semicolon (;) is used to separate each statements.
  2. The curly brackets ({ }) must be used on several functions such as if, for, and while if there are more than one statements that will be executed in the function.
  3. C++ is a case-sensitive programming language, so if you use capitalization incorrectly, the compiler will give an error message.
  4. To set the value of char and string data types or to print text on a program, double quotation mark (“ “) is necessary.
  5. For comments, we use double slash (//) to mark the following text in a line as comment or type them between /* and */ to mark several lines of code or text as comments.

Here are an example of a program with correct syntax in C++:

#include <iostream>

using namespace std;

int main() {

int x,y,z;

cout<<“Masukkan nilai x dan y : “;

cin>> x >> y;

fflush(stdin);

 

z=x+y;

 

if (z>50) cout<<“Jumlah dari x dan y lebih dari 50”;

else cout<<“Jumlah dari x dan y kurang dari 50”;

 

getchar();

return 0;

}

Semantics

The requirements for a methodology and notation for semantics are as follows:

  • Programmers need to know what statements mean
  • Compiler writers must know exactly what language constructs do
  • Correctness proofs would be possible
  • Compiler generators would be possible
  • Designers could detect ambiguities and inconsistencies

There are some kinds of semantics:

  • Operational semantics, which describes the meaning of a program directly by executing its statements on a machine, either simulated or actual. The change in the state of the machine (memory, registers, etc.) defines the meaning of the statement.
  • Denotational semantics, where each phrase in the language is interpreted as a denotation, i.e. a conceptual meaning that can be thought of abstractly.
  • Axiomatic semantics, where axioms or inference rules are defined for each statement type in the language (to allow transformations of logic expressions into more formal logic expressions).
  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • Twitter
  • RSS

PLC – Chapter 1 – Introduction

A.    Reasons for Studying Concepts of Programming Languages

  • Increased ability to express ideas.
    • It is believed that the depth at which we think is influenced by the expressive power of the language in which we communicate our thoughts. It is difficult for people to conceptualize structures they can’t describe, verbally or in writing.
    • Language in which they develop software places limits on the kinds of control structures, data structures, and abstractions they can use.
  • Improved background for choosing appropriate languages.
    • Many programmers, when given a choice of languages for a new project, continue to use the language with which they are most familiar, even if it is poorly suited to new projects.
    • If these programmers were familiar with other languages available, they would be in a better position to make informed language choices.
  • Greater ability to learn new languages.
    • Programming languages are still in a state of continuous evolution, which means continuous learning is essential.
    • Programmers who understand the concept of OO programming will have easier time learning Java.
    • Once a thorough understanding of the fundamental concepts of languages is acquired, it becomes easier to see how concepts are incorporated into the design of the language being learned.
  • Understand significance of implementation.
    • Understanding of implementation issues leads to an understanding of why languages are designed the way they are.
    • This in turn leads to the ability to use a language more intelligently, as it was designed to be used.
  • Ability to design new languages.
    • The more languages you gain knowledge of, the better understanding of programming languages concepts you understand.
  • Overall advancement of computing.
    • Many believe that ALGOL 60 was a better language than Fortran; however, Fortran was most widely used. It is attributed to the fact that the programmers and managers didn’t understand the conceptual design of ALGOL 60.

B.     Programming Domains

  • Scientific applications
    • In the early 40s computers were invented for scientific applications.
    • The applications require large number of floating point computations.
    • Fortran was the first language developed scientific applications.
    • ALGOL 60 was intended for the same use.
  • Business applications
    • The first successful language for business was COBOL.
    • Produce reports, use decimal arithmetic numbers and characters.
    • The arrival of PCs started new ways for businesses to use computers.
    • Spreadsheets and database systems were developed for business.
  • Artificial intelligence
    • Symbolic rather than numeric computations are manipulated.
    • Symbolic computation is more suitably done with linked lists than arrays.
    • LISP was the first widely used AI programming language.
  • Systems programming
    • The operation system and all the programming supports tools are collectively known as its system software.
    • Need efficiency because of continuous use.

 

  • Scripting languages
    • Put a list of commands, called a script, in a file to be executed.
    • PHP is a scripting language used on Web server systems. Its code is embedded in HTML documents.  The code is interpreted on the server before the document is sent to a requesting browser.

C.    Language Evaluation Criteria

  • Readability
  • Language constructs were designed more from the point of view of the computer than the users.
  • Because ease of maintenance is determined in large part by the readability of programs, readability became an important measure of the quality of programs and programming languages. The result is a crossover from focus on machine orientation to focus on human orientation.
  • The most important criteria “ease of use”
  • Orthogonality
    • Makes the language easy to learn and read.
    • Meaning is context independent. Pointers should be able to point to any type of variable or data structure.  The lack of orthogonality leads to exceptions to the rules of the language.
    • A relatively small set of primitive constructs can be combined in a relatively small number of ways to build the control and data structures of the language.
    • Every possible combination is legal and meaningful.
    • The more orthogonal the design of a language, the fewer exceptions the language rules require.
    • The most orthogonal programming language is ALGOL 68. Every language construct has a type, and there are no restrictions on those types.
    • This form of orthogonality leads to unnecessary complexity.

➢    Writability

  • It is a measure of how easily a language can be used to create programs for a chosen problem domain.
  • Most of the language characteristics that affect readability also affect writability.
  • Simplicity and orthogonality
    • A smaller number of primitive constructs and a consistent set of rules for combining them is much better than simply having a large number of primitives.
  • Support for abstraction
    • Abstraction means the ability to define and then use complicated structures or operations in ways that allow many of the details to be ignored.
    • A process abstraction is the use of a subprogram to implement a sort algorithm that is required several times in a program instead of replicating it in all places where it is needed.
  • Expressivity
    • It means that a language has relatively convenient, rather than cumbersome, ways of specifying computations.

➢    Reliability

  • A program is said to be reliable if it performs to its specifications under all conditions.
  • Type checking: is simply testing for type errors in a given program, either by the compiler or during program execution.
    • The earlier errors are detected, the less expensive it is to make the required repairs. Java requires type checking of nearly all variables and expressions at compile time.
  • Exception handling: the ability to intercept run-time errors, take corrective measures, and then continue is a great aid to reliability.
  • Aliasing: it is having two or more distinct referencing methods, or names, for the same memory cell.
    • It is now widely accepted that aliasing is a dangerous feature in a language.
  • Readability and writability: Both readability and writability influence reliability.

➢    Cost

•      Categories

  • Training programmers to use language
  • Writing programs “Writability”
  • Compiling programs
  • Executing programs
  • Language implementation system “Free compilers is the key, success of Java”
  • Maintaining programs: Maintenance costs can be as high as two to four times as much as development costs.
  • Portability “standardization of the language”
  • Generality (the applicability to a wide range of applications)

D.    Influences on Language Design

  • Computer architecture: Von Neumann
  • We use imperative languages, at least in part, because we use von Neumann machines
    • Data and programs stored in same memory
    • Memory is separate from CPU
    • Instructions and data are piped from memory to CPU
    • Results of operations in the CPU must be moved back to memory
    • Basis for imperative languages
      • Variables model memory cells
      • Assignment statements model piping
      • Iteration is efficient

a

  • Program Design Methodologies
  • New software development methodologies (e.g., object-oriented software development) led to new programming paradigms and by extension, new programming languages

➢    Programming methodologies

  • 1950s and early 1960s: Simple applications; worry about machine efficiency
  • Late 1960s: People efficiency became important; readability, better control structures
    • Structured programming
    • Top-down design and step-wise refinement
  • Late 1970s: Process-oriented to data-oriented
    • data abstraction
  • Middle 1980s: Object-oriented programming
  • Data abstraction + inheritance + polymorphism

E.Language Categories

  • Imperative
    • Central features are variables, assignment statements, and iteration
    • C, Pascal
  • Functional
    • Main means of making computations is by applying functions to given parameters
    • LISP, Scheme
  • Logic
    • Rule-based
    • Rules are specified in no special order
    • Prolog
  • Object-oriented
    • Encapsulate data objects with processing
    • Inheritance and dynamic type binding
    • Grew out of imperative languages
    • C++, Java
  1. Implementation Methods
  • Compilation
  • Programs are translated into machine language; includes JIT systems
  • Use: Large commercial applications
  • Pure Interpretation
  • Programs are interpreted by another program known as an interpreter
  • Use: Small programs or when efficiency is not an issue
  • Hybrid Implementation Systems
  • A compromise between compilers and pure interpreters
  • Use: Small and medium systems when efficiency is not the first concern

Layered View of Computer

b

  • Compilation
  • Translate high-level program (source language) into machine code (machine language)
  • Slow translation, fast execution
  • Compilation process has several phases:
    • lexical analysis: converts characters in the source program into lexical units
    • syntax analysis: transforms lexical units into parse trees which represent the syntactic structure of program
    • Semantics analysis: generate intermediate code
    • code generation: machine code is generated

The Compilation Process

c

  • Pure Interpretation
  • No translation
  • Easier implementation of programs (run-time errors can easily and immediately be displayed)
  • Slower execution (10 to 100 times slower than compiled programs)
  • Often requires more space
  • Now rare for traditional high-level languages
  • Significant comeback with some Web scripting languages (e.g., JavaScript, PHP)

Pure Interpretation Process

d

  • Hybrid Implementation Systems
  • A compromise between compilers and pure interpreters
  • A high-level language program is translated to an intermediate language that allows easy interpretation
  • Faster than pure interpretation
  • Examples
    • Perl programs are partially compiled to detect errors before interpretation
    • Initial implementations of Java were hybrid; the intermediate form, byte code, provides portability to any machine that has a byte code interpreter and a run-time system (together, these are called Java Virtual Machine)

Hybrid Implementation Process

e

 

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • Twitter
  • RSS

HIMTI Togetherness and Top Performance 2016

HEADER TANPA MENU.png

HTTP 2016

Passion, Innovation, and Togetherness. Slogan yang diangkat oleh HIMTI(Himpunan Mahasiswa Teknik Informatika) Binus University dalam acara HIMTI Togetherness and Top Performance(HTTP) 2016. HTTP sendiri diadakan setiap tahunnya oleh HIMTI untuk menyambut mahasiswa baru School of Computer Science(SoCS) Binus University.

HTTP tahun ini dilaksanakan pada tanggal 10 September 2016 bertempat di Auditorium Lt.3 Gedung BPPT 2, Jl.M.H.Thamrin No.8, Jakarta Pusat. Untuk acara HTTP 2016, tiketnya dibanderol dengan harga Rp. 150.000. Awalnya harga tersebut terlihat sedikit mahal, namun banyak benefit yang didapatkan dari acara HTTP 2016.

Benefit pertama yang didapatkan oleh peserta adalah pengenalan bahasa C atau yang disingkat dengan PBC. Sesuai dengan namanya, PBC ini memiliki tujuan untuk memperkenalkan bahasa C kepada peserta yang sudah membeli tiket HTTP 2016.

Benefit kedua yang didapatkan oleh peserta adalah transportasi. Para peserta yang tidak memiliki transportasi pribadi untuk pergi menuju lokasi acara, dapat pergi bersama-sama dengan bus yang sudah disediakan oleh panitia HTTP 2016. Para peserta HTTP 2016 yang berasal dari daerah Kemanggisan berkumpul di Kampus Binus Anggrek pada jam 06.30 WIB untuk peserta yang memilih shift 1 dan jam 07.45 WIB untuk peserta yang memilih shift 2. Dan untuk Kampus Binus Alam Sutera berangkat dari jam 06.00 WIB.

Para peserta yang sudah tiba di lokasi acara diwajibkan untuk melakukan registrasi ulang, dan dapat melihat showcase aplikasi-aplikasi yang diciptakan oleh para senior. Sebelum acara dimulai para peserta disuguhkan sebuah film berjudul Zootopia, yang pada akhirnya tidak selesai diputar padahal lagi seru, karena waktu sudah menunjukan kurang lebih pukul sembilan, sehingga acara sudah harus dimulai.

Acara dibuka dengan beberapa penampilan, lalu dilanjutkan dengan beberapa kata sambutan. Lalu setelah beberapa saat acara dilanjutkan dengan talkshow dari 3 orang narasumber, yang seorang berhasil membuat alat pendeteksi kepribadian melalui tweet di twitter, dan 2 orang lainnya membuat robot yang bisa berbahasa indonesia.

463211

Talkshow ( maaf kameranya jelek )

Setelah talkshow dan beberapa acara lainnya selesai, sempat dilaksanakan break makan siang yang juga merupakan benefit ke tiga dari HTTP 2016 ini adalah mereka memberikan makan siang kepada peserta. Selama break juga peserta dapat berkeliling area acara dimana ada dibukanya beberapa stand makanan.

Setelah break selesai, acara dilanjutkan hingga menuju segmen visualisasi, dimana para pengurus HIMTI menampilkan sebuah drama yang cukup menghibur, bertujuan untuk mengenalkan HIMTI kepada para peserta.

463218

Visualisasi ( ada sedikit pemandangan di sebelah kiri foto )

463220

Visualisasi ( masih disebelah kiri )

Setelah visualisasi berakhir dan dilanjutkan beberapa acara hingga akhirnya para peserta disuguhkan dengan penampilan dance, dan ada lucky draw, lalu ada nya penampilan dari guest star, dan diakhiri oleh hal yang ditunggu-tunggu oleh banyak peserta yaitu penampilan DJ.

Setelah acara berakhir dengan diakhiri oleh musik DJ, para peserta acara mulai berpulangan, untuk yang tadi pergi menggunakan transportasi yang disediakan oleh panitia HTTP 2016, dapat menaiki bus lagi untuk pulang menuju tempat kumpul pertama. Namun, sebelum peserta pulang, setiap peserta mendapatkan sebuah tas yang merupakan benefit terakhir dari HTTP yaitu, merchandise, T-Shirt, pin, dan sebuah pembatas buku yang dapat memberikan akses menuju HIMTI Kit. HIMTI Kit sendiri merupakan aplikasi-aplikasi penunjang selama perkuliahan. Mahasiswa yang mengikuti HTTP 2016 ini juga mendapatkan e-Certificate.

Sekian laporan acara HTTP 2016, mohon maaf jika ada salah kata.

HIMTI
One Family, One Goal

 

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • Twitter
  • RSS

Hello world!

Welcome to Binusian blog.
This is the first post of any blog.binusian.org member blog. Edit or delete it, then start blogging!
Happy Blogging 🙂

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • Twitter
  • RSS
 Page 2 of 2 « 1  2