Saturday, 5 May 2012

Chapter 3 : FUNDAMENTALS OF PROGRAMMING LANGUAGE

CHAPTER 3: FUNDAMENTALS OF PROGRAMMING LANGUAGE

Define data type.

When programming, we store the variables in our computer's memory, but the computer has to know what kind of data we want to store in them, since it is not going to occupy the same amount of memory to store a simple number than to store a single letter or a large number, and they are not going to be interpreted the same way.

Basic fundamental data types in C++, as well as the range of values that can be
represented with each one:

Name
Description
Size*
char
Character or small integer.
1byte
int
Integer.
4 bytes
bool
Boolean value. It can take one of two values: true
or false.

1 byte
float
Floating point number.
4 bytes
double
Double precision floating point number.
8 bytes

* The values of the columns Size depend on the system the program is compiled for. The values shown above are those found on most 32-bit systems. But for other systems, the general specification is that int has the natural size suggested by the system architecture (one "word") and the four integer types char must each one be at least as large as the one preceding it, with char being always 1 byte in size. The same applies to the floating point types float, double  where each one must provide at least as much precision as the preceding one.

Types of data:

a.    Numeric

Numberic data are numbers (like age, cost)

b.    Non-numeric

non-numeric data are not numbers (like name, address).

 

The memory in our computers is organized in bytes. A byte is the minimum amount of memory that we can manage in C++. A byte can store a relatively small amount of data: one single character or a small integer (generally an integer between 0 and 255). In addition, the computer can manipulate more complex data types that come from grouping several bytes, such as long numbers or non-integer numbers.

a.  Bit the on/off state (0 or 1)
                       b. Byte – 8 bits
                     c. Field - one or more byte
                     d. Record - combined field about a thing, person, place.  E.g. collection of      fields
                     e. File - a collection of records
                     f. Database - one of more files

Define identifier

A valid identifier is a sequence of one or more letters, digits or underscore characters (_). Neither spaces nor punctuation marks or symbols can be part of an identifier. Only letters, digits and single underscore characters are valid. In addition, variable identifiers always have to begin with a letter. They can also begin with an underline character (_ ), but in some cases these may be reserved for compiler specific keywords or external identifiers, as well as identifiers containing two successive underscore characters anywhere. In no case they can begin with a
digit.

Very important: The C++ language is a "case sensitive" language. 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 RESULT variable is not the same as the result variable or the Result variable. These are three different variable identifiers.


Variable

A variable whose value cannot be changed once it has been assigned a value.
In order to use a variable in C++, we must first declare it specifying which data type we want it to be. The syntax to declare a new variable is to write the specifier of the desired data type (like int, bool, float...) followed by a valid variable identifier. For example:

int a;
float mynumber;

These are two valid declarations of variables. The first one declares a variable of type int with the identifier a. The second one declares a variable of type float with the identifier mynumber. Once declared, the variables a and mynumber can be used within the rest of their scope in the program.

If you are going to declare more than one variable of the same type, you can declare all of them in a single statement by separating their identifiers with commas. For example:

int a, b, c;

This declares three variables (a, b and c), all of them of type int, and has exactly the same meaning as:

int a;
int b;
int c;

To see what variable declarations look like in action within a program, we are going to see the C++ code of the example about your mental memory proposed at the beginning of this section:
// operating with variables
#include <iostream>
using namespace std;
int main ()
{

// declaring variables:
int a, b;
int result;

// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;

// print out the result:
cout << result;

// terminate the program:
return 0;
}

Output :

4


Constant

A constant is an identifier whose associated value cannot typically be altered by the program during its execution. Although a constant's value is specified only once, a constant may be referenced many times in a program.

Example :

#define PI 3.1415926535

const float pi2 = 3.1415926535;




For example :


#define PI 3.14159
#define NEWLINE '\n'

This defines two new constants: PI and NEWLINE. Once they are defined, you can use them in the rest of the code as if they were any other regular constant, for example:

// defined constants: calculate circumference
#include <iostream>
using namespace std;
#define PI 3.14159
#define NEWLINE '\n'
int main ()
{
double r=5.0; // radius
double circle;
circle = 2 * PI * r;
cout << circle;
cout << NEWLINE;
return 0;
}

Output :

31.4159

In fact the only thing that the compiler preprocessor does when it encounters #define directives is to literally replace any occurrence of their identifier (in the previous example, these were PI and NEWLINE) by the code to which they have been defined (3.14159 and '\n' respectively).
The #define directive is not a C++ statement but a directive for the preprocessor; therefore it assumes the entire line as the directive and does not require a semicolon (;) at its end. If you append a semicolon character (;)at the end, it will also be appended in all occurrences within the body of the program that the preprocessor replaces.


Solve problem using operators in a program.
          
                a. Arithmetic operators

Arithmetic operators are used to perform many of the familiar arithmetic operations that involve the calculation of numeric values

For example, let us have a look at the following code

// assignment operator
#include <iostream>
using namespace std;
int main ()
{
int a, b; // a:?, b:?
a = 10; // a:10, b:?
b = 4; // a:10, b:4
a = b; // a:4, b:4
b = 7; // a:4, b:7
cout << "a:";
cout << a;
cout << " b:";
cout << b;
return 0;
}

Output :

a:4 b:7


The five arithmetical operations supported by the C++ language are:
a)    + addition
b)    – substraction
c)    * multiplication
d)    / division
e)    % modulo

Operations of addition, subtraction, multiplication and division literally correspond with their respectivemathematical operators. The only one that you might not be so used to see is modulo; whose operator is the percentage sign (%). Modulo is the operation that gives the remainder of a  division of two values. For example, if we write:

a = 11 % 3;

the variable a will contain the value 2, since 2 is the remainder from dividing 11 between 3. 

When we want to modify the value of a variable by performing an operation on the value currently stored in that variable we can use compound assignment operators:

expression is equivalent to

value += increase; value = value + increase;
a -= 5; a = a - 5;
a /= b; a = a / b;
price *= units + 1; price = price * (units + 1);



Increase and decrease (++, --)

Shortening even more some expressions, the increase operator (++) and the decrease operator (--) increase or reduce by one the value stored in a variable. They are equivalent to +=1 and to -=1, respectively. Thus:
c++;
c+=1;
c=c+1;
are all equivalent in its functionality: the three of them increase by one the value of c.

A characteristic of this operator is that it can be used both as a prefix and as a suffix. That means that it can be written either before the variable identifier (++a) or after it (a++). Although in simple expressions like a++ or ++a

both have exactly the same meaning, in other expressions in which the result of the increase or decrease operation is evaluated as a value in an outer expression they may have an important difference in their meaning: In the case that the increase operator is used as a prefix (++a) the value is increased before the result of the expression is evaluated and therefore the increased value is considered in the outer expression; in case that it is used as a suffix (a++) the value stored in a is increased after being evaluated and therefore the value stored before the increase
operation is evaluated in the outer expression. Notice the difference:

A
B
B=3;
A=++B;
// A contains 4, B contains 4
B=3;
A=B++;
// A contains 3, B contains 4

In Example 1, B is increased before its value is copied to A. While in Example 2, the value of B is copied to A and then B is increased.


b.    Relational operators

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

In order to evaluate a comparison between two expressions we can use the relational and equality operators. The result of a relational operation is a Boolean value that can only be true or false, according to its Boolean result. We may want to compare two expressions, for example, to know if they are equal or if one is greater than the other is. Here is a list of the relational and equality operators that can be used in C++:

== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Here there are some examples:

(7 == 5) // evaluates to false.
(5 > 4) // evaluates to true.
(3 != 2) // evaluates to true.
(6 >= 6) // evaluates to true.
(5 < 5) // evaluates to false.

Of course, instead of using only numeric constants, we can use any valid expression, including variables. Suppose that a=2, b=3 and c=6,
(a == 5) // evaluates to false since a is not equal to 5.
(a*b >= c) // evaluates to true since (2*3 >= 6) is true.
(b+4 > a*c) // evaluates to false since (3+4 > 2*6) is false.
((b=2) == a) // evaluates to true.

Be careful! The operator = (one equal sign) is not the same as the operator == (two equal signs), the first one is an assignment operator (assigns the value at its right to the variable at its left) and the other one (==) is the equality operator that compares whether both expressions in the two sides of it are equal to each other. Thus, in the last expression ((b=2) == a), we first assigned the value 2 to b and then we compared it to a, that also stores the value 2, so the result of the operation is true.

c.    Logical operators

Logical operators ( !, &&, || )

The Operator ! is the C++ operator to perform the Boolean operation NOT, it has only one operand, located at its right, and the only thing that it does is to inverse the value of it, producing false if its operand is true and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand. For example:

!(5 == 5) // evaluates to false because the expression at its right (5 == 5) is true.
!(6 <= 4) // evaluates to true because (6 <= 4) would be false.
!true // evaluates to false
!false // evaluates to true.

The logical operators && and || are used when evaluating two expressions to obtain a single relational result. The operator && corresponds with Boolean logical operation AND. This operation results true if both its two operands are true, and false otherwise. The following panel shows the result of operator && evaluating the expression a && b:

a
b
a&& b
true
true
true
true
false
false
false
true
false
false
false
false

The operator || corresponds with Boolean logical operation OR. This operation results true if either one of its two operands is true, thus being false only when both operands are false themselves. Here are the possible results of a || b:

a
b
a|| b
true
true
true
true
false
true
false
true
true
false
false
false



Program control structures.

All computer programs, no matter how simple or how complex, are written using one or more of three basic structures:

a)    Sequence                               
b)    Selection
c)    Repetition

These structures are called control structures or logic structures, because they control the flow of a program’s logic.

The algorithms for all computer programs contain one or more of the following three control structures: sequence, selection, and repetition

         
a.    Sequence

The sequence structure in a computer program directs the computer to process the program instructions, one after another, in the order listed in the program

 
Example 1: The following sequence of statements read a number, double it, and then output the result
int num;
read  num;
int doublenum = num * 2;
   print doublenum;

Example 2: The following sequence of statements convert Celsius to Fahrenheit


float tempC;
float tempF;
read tempC;
tempF = (tempC * 9 / 5) + 32;
print tempF;


b.    Selection

Like the sequence and repetition structures, you already are familiar with the selection structure, also called the decision structure. The selection structure makes a decision, and then takes an appropriate action based on that decision. The selection structure also provides the appropriate action to take based on the result of that decision
Example 1:
In checking an account balance, the following code segment prints the message “Account overdrawn” if the balance is < 0.

if  AccountBalance < 0
    print “Account overdrawn”
endif


Example 2:
The following if statement is part of the logic of a routine to determine a student’s letter grade based on the student’s average score.
if  StudentAverage > 89.5
    print ‘A’


Example 3:
This example makes use of a boolean variable (which is evaluated to be ‘true’ or ‘false’). The if statement tests to see if a customer has a discount coupon (yes or no: true or false), and sets a discount rate of 15% if the coupon exists:
if  DiscountCoupon
    DiscountRate = 0.15
endif
Cost = Price - DiscountRate*Price


                c. Repetition

When used in a program, the repetition structure, also referred to as a loop, directs the computer to repeat one or more instructions until some condition is met, at which time the computer should stop repeating the instructions

Notice that the instruction to be repeated—in this case, walk—is indented below the repeat 50 times:instruction. Indenting in this manner indicates the instructions that are part of the repetition structure, and therefore, are to be repeated
Example 1 :

 Develop an algorithm to add (find the sum) of the positive integers from 1 to 100. Using a while loop, the solution is given by
int Sum = 0
int N = 0
while N < 100
    N = N + 1
    Sum = Sum  +  N
endwhile









 

 

 

 

 

 

 

 

 

Rujuk :

http://www.cplusplus.com/files/tutorial.pdf

www.nvcc.edu/home/kkamal/L_03.doc