Anda di halaman 1dari 9

CHAPTER 2: BASIC ELEMENTS OF COMPUTER

IDENTIFIER, VARIABLE AND CONSTANT IDENTIFIER Identifiers are used to define names to represent variables, constant and name of function. Identifiers are formed by combining letters (both uppercase and lowercase), digits and the underscore (_). The rules for naming identifiers are as follows: i. The first character of an identifier must be a letter or an underscore ( _ ). Example of valid identifiers: Form1 _2nd_class side_3

PROGRAMS

Example of invalid identifiers: 3number 8tv1 1_to_0

ii.

Only letters, digits or underscores may follow the initial letter. Special characters such as #, $, %, @, !, , - blank or whitespaces and etc are NOT ALLOWED; either used the underscore to separate the words in a name consisting of multiple words or capitalize the first letter of one or more words. Example of valid identifiers: MilesToKilo kilo_to_miles kilo2miles Example of invalid identifiers: Total$ km/hour comm.%

iii.

Must not be keywords or reserved words. A keyword or reserve word is a word that is set aside by the language for a special purpose and can only be used in a specified manner. For example: C++ keywords such as cin , cout, return cannot be used as identifier name. Example of keywords or reserved words: 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 Identifiers are case-sensitive For example, NUM1, num1, Num1 are three different identifiers. 1

iv.

(Reference: Problem solving With C++ (Norizan Mohamad & Mazidah Puteh (UiTM))

v.

Identifiers must be mnemonic or meaningful code or word that reflects the data items they store. For example, TOTAL scores the result of an arithmetic operation; PI stores the PI value (3.142) and etc. Examples of meaningful identifiers: Number value name total Examples of valid identifiers but are not meaningful: R3s4 n1 nike hardy po52

MORE EXAMPLES: Valid Invalid x 2sumx hourly-rate name@ GROSS PAY Reason Invalid Character not allowed Begin with a number 2 Hyphen not allowed Character @ not allowed Illegal blank

x
sumx2 hourly_rate name GROSS_PAY VARIABLE

Variable is an identifier that refers to memory location, which can hold values. Variable can only store one value at one time. Thus, the content of variable may change during the program execution.

Variable Declaration All variables must be declared before they can be used in the program. The general form of the declaration is: data_type variable_name; int
int float num; value;

nombor;
// reserving a memory location called num to hold an //integer value //reserving a memory location called value to hold a //floating-point number //reserving a memory location called total to hold a //double-precision number //reserving a memory location called grade to hold a //character //reserving a memory location called name to hold 20 //characters //reserving a memory location datnum to hold a long //integer

Example of variable declaration:

double total; char char long grade; name[20]; datnum;

One variable is declared, it contains no useful value (garbage). To make it useful, the variable must be given a value, either by the assignment statement or input from the user, before it is used. 2
(Reference: Problem solving With C++ (Norizan Mohamad & Mazidah Puteh (UiTM))

This value serves as the initial value to the variable. Example of variable initialization:
num=10; //sets the initial value of 10 into the variable num suing //assignment statement

It is a good programming practice to declare and initialize a variable using assignment statement on the same line. This will also reduce the length of a program. Example of variable declaration AND initialization:
int num=10; float number = 5.5; //declaration num as integer variable and sets the value of //10 into num //declare number as a float variable and sets the value of //5.5 into number

Multiple Variables Declaration Variables having the same data type can be grouped together and declared using a single-declaration statement. For example, the following declaration statements: int num1; int num2; int sum; Can be written a s a single statement int num1, num2, sum; Another example to assign values to the variable num1, num2 and sum with the initial 10, 20, 0 respectively, the C++ statement can be written as: int num1 = 10, num2 = 20, total = 0; The following example gives all the variables the value 0 score1 = score2= score3 =0;

CONSTANT Constant are identifiers with fixed value and do not change throughout the program execution. The general form of the constant declaration and definition is const data_type variable_name; const int MONTHINYEAR=12; const float PI=3.142; It is common practice to use capital letters for constant names distinguish them visually from other variables. Once declared as constants, the variables cannot be modified within program. Otherwise, it will cause a syntax error. DATA TYPE 3
(Reference: Problem solving With C++ (Norizan Mohamad & Mazidah Puteh (UiTM))

Identifiers that store data, such as variables and constants must be given the data type. The data types specify the type and size of data identifiers can hold. Generally there are several data types available as follow: i. Numeric data type a) Integer (int, long int) A whole number, which may be +ve, zero or ve. Integers vary in size between systems. Therefore to process integers outside the range of -32768 to 32767, long integers are normally used.

b) Floating point (float, double) ii. Data of type float ranges approximately 6 to 7 digits of precision whilst double takes approximately 13 decimal digits of precision.

Character data type Single character (char) If a variable is declared as char data type, it can only store one character value (a letter, digit or special symbol). In C++ the single character is enclosed in a single quotation mark ( ).

Example: char grade =A; //stores character A into variable grade String of characters (char [ ] ) In C++, a string is defined as a sequence of characters that is terminated by a null character, \0 which has the value of zero. The null character denotes the end of a string and is added to the string by the compiler automatically. Because of the null terminator, it is necessary to declare a string with one character longer than the actual size it can hold. If the size of a string is shorter than the value is stored into the string, the value will be truncated. For example to declare a string that could hold 5 characters, the following statement is written. char text[8] = Welcome; // 8 is one character longer than 7 In the following graphical representation, the string text can be represented as an array of characters where the first index of an array begins with the index 0. e [1] l [2] c [3] o [4] m [5] e [6] \0 [7] 4
(Reference: Problem solving With C++ (Norizan Mohamad & Mazidah Puteh (UiTM))

Index

W [0]

Value for the strings are enclosed in quotation marks ( ), which are not themselves part of the string. Blank spaces and characters other than letters are also included as part of the string, if used.

iii.

Constant data type Constants are value that are fixed and do not change throughout the program execution. Example: const int days_a_week = 7; Boolean data type The data type bool has only two values: TRUE and FALSE. Also, true and false are called the logical (Boolean) values. The central purpose of this data type is to manipulate logical (Boolean) expressions.

iv.

SUMMARY OF STANDARD OF DATA TYPE


Data types Integer Long integer Character String Floating point Double floating point Constant Boolean Keyword (C+ +) int long char char [ ] float double const bool Bits 16 32 8 Range -32768 to 32767 -4294967296 to 4295967295 0 to 255 Examples 45, 0, -10 34567, -45676, 124566789 x, N, $ hello Malik Student id 32.88, -89.56 12.789987845, -25.12345678 Pi=3.142 True False

32 64

Approximately 6 to 7 digits of precision Approximately 13 digits of precision

OPERATORS An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C++ has the following operators: 1. Arithmetic operators 2. Relational operators 3. Logical operators 4. Assignment operators

ARITHMETIC OPERATORS Integers and real numbers may be added, subtracted, divided and multiplied. To perform arithmetic operations, the arithmetic operators are used. The following table summarizes the arithmetic operators. 5
(Reference: Problem solving With C++ (Norizan Mohamad & Mazidah Puteh (UiTM))

Arithmetic operations Subtraction Addition Multiplication Division Modulus division Decrement by 1 Increment by 1 Syntax form: Operand X operator +

Arithmetic operators + * / % -++ operand Y

In performing an operation, the following rules must be considered: 1. If both operands are integer, then the result is an integer. 2. If any operand is a floating point value, the result is a floating point.

Integer Division Dividing an integer by another integer will result in an integer result. Thus 5/2 is 2 and NOT 2.5. Because integer cannot contain fractional part, a result such as 2.5 cannot be obtained. In C++, the fractional part of the result is dropped. To capture the remainder of an integer division, C++ provides a modulus operator (represented by symbol %) to be implemented only for integers. Thus 5 % 2 is 1. Example: Given int a=7, b=2; The following shows the memory content and the result after the execution of the statement. Expression a-b a+b a*b a/b a%b a-b++ Memory content 7-2 7+2 7*2 7/2 7%2 7-1 2+1 Value 5 9 14 3 1 6 3

More than one operator can be combined to form one arithmetic expression. For example, sum = num1/num2 * 3 + 4; In C++ the order of evaluating the arithmetic operation becomes important. The precedence of evaluation from highest to lowest is summarized below: Operator () Operation Parenthesis Precedence Evaluated first. If nested parenthesis, the 6

(Reference: Problem solving With C++ (Norizan Mohamad & Mazidah Puteh (UiTM))

*/ % + =

Multiply, division, modulus Add, sub assignment

innermost pair is evaluated first. If not nested, and on the same level, it is evaluated left to right. Will be evaluated next, from left to right Will be evaluated next, from left to right Will be last evaluated from left to right

Based on the above hierarchy of operators, the statement Total = 8 / 2 * 3 + 4 * 5 % 3;

Will be processed as follows: Steps 1 2 3 4 5 Operations 8/2 4*3 4*5 10 % 3 12 + 2 Result 4 12 20 2 14

Finally, the result 14 will be stored in Total.

RELATIONAL OPERATORS Relational operators are used for comparing the values of two operands as follows. The evaluation result is an expression is either TRUE (represented by non-zero) or FALSE (represented by 0). Comparison Less than Less than or equal Greater than Greater than or equal Equal Not equal Relational operators < <= > >= == != Example count<10 income<=2000 year>20 marks>=90 total==0 num!=1

Boolean Expression Is an expression in which two arithmetic values are compared using single relational operator. Each Boolean expression has the Boolean value TRUE or FALSE according to arithmetic validity of the expression. Example: Given a = 4 and b = 10, i. The expression a < b is TRUE or 1 7
(Reference: Problem solving With C++ (Norizan Mohamad & Mazidah Puteh (UiTM))

ii.

The expression a == b is FALSE or 0

LOGICAL OPERATORS When there is more than one relational expression at a time, logical operator are used to perform the evaluation. To perform logical operations, logical operator to be used are shown below:
Logical operations AND OR NOT Operators && || ! Example (a<b) && (a< c) (a==b) || (a==c) Num !=999

Truth Table X True True Fals e Fals e A truth table is used to specify the conditions that make a logical operation true and false. A truth table lists all possible combinations of operand values and the result of the operation for each combination. The truth table for logical operation is summarized below: Y True False True False
X && Y (both X and Y must be TRUE) X || Y (either X or Y must be TRUE) !X (produces the opposite relation)

True False False False

True True True False

False False True True

Hierarchy of Operators (Operator Precedence) The operator precedence determines its order of evaluation in an expression. The following table shows the precedence from highest to lowest of all common C++ operators.
Operator category (highest to lowest) Parenthesis Unary operators, Logical NOT Multiply, divide, remainder Add, subtract Operator (from left to right)

() + , - , ++, -- , ! */ % + 8

(Reference: Problem solving With C++ (Norizan Mohamad & Mazidah Puteh (UiTM))

Relational operator Equality operators Logical AND Logical OR Assignment

<

<= > >= == != && || =

ASSIGNMENT OPERATOR The assignation operator serves to assign a value to a variable. Example: a = 5; Assigns the integer value 5 to variable a. The part at the left of the = operator is known as lvalue (left value) and the right one as rvalue (right value). lvalue must always be a variable whereas the right side can be either a constant, a variable, the result of an operation or any combination of them. It is necessary to emphasize that the assignation operation always takes place from right to left and never at the inverse. a = b;

9
(Reference: Problem solving With C++ (Norizan Mohamad & Mazidah Puteh (UiTM))

Anda mungkin juga menyukai