Lesson 2 C Basics C is a highlevel

Lesson 2 C++ Basics C++ is a high-level programming language developed by Bjarne Stroustrup in early 80 s. He is a professor at Texas A&M Univ. now. 1

Features of C++ Ø General purpose C As general as C or Pascal. Ø Object oriented C++ is formed by adding OOP features in C. Ø Suitable for software development in general. Ø Efficient. A C++ program runs faster than its Java counterpart. Ø Insecure. The execution of a malicious C++ program can cause serious damage on a computer. Ø Portable A C++ program can be executed on any computer with a 2 C++ compiler, theoretically.

Compilation and Linking Ø Source code A C++ program (a text file with the suffix. cpp) C++ program Compiler object code Ø Object code A compiler translates a C++ program into a machine language program. The output is a binary file with the suffix. obj 3

object code of library programs object code of a prog. Linker Executable code Ø Executable code (. exe) An object code program is linked with the object code of other build-in programs in libraries. A linker is a program that carries out the linking operation. The output of a linker is called executable code, a binary file with the suffix. exe 4

Ø Execution An executable code program is first loaded in RAM by a loader before the execution. Executable code loader Executable code Computer DISK RAM 5

Ø An Integrated Development Environment (IDE) is a software that provides editing, compiling, linking, loading, execution and other services for developing programs. Ø In this course, we will use the Bloodshed Dev-C++ IDE for writing C++ programs. The software is free and can be easily downloaded from the Internet. 6

A simple C++ program This program outputs the green string. ‘n’ is a newline character. //hello. cpp #include <iostream> using namespace std; int main() { cout << ("Hello, C++ freaks!n"); system("PAUSE"); return 0; } Run the program 7

Ø A bit is the smallest storage element in a computer whose value is either 0 or 1 (a binary digit) Ø A byte consists of eight bits. A byte is the smallest addressable unit in RAM Ø A character is represented using one byte in extended ASCII code Ø Types of characters ØLetters: A, B, …, Z, a, b, …, z, $, _ ØDigits: 0, 1, …, 9 ØOthers: +, -, *, /, … Ø A string is a sequence of characters delimited in a pair of double quotes, eg, “SARS”, “I love HKU. ” 8

Ø 7 -bit American Standard Code for Information Interchange (ASCII) character set. Ø E. g. , A is 41 H=0100 0001, w is 77 H=0111 10 11 12 9

Ø A text file is a collection of characters stored in a disk Ø The source code of a C++ program consists of characters. It is stored as a text file with the extension. cpp, eg, hello. cpp Ø One or more characters in a C++ program form a token Ø Types of tokens Ø Identifiers (Names): Hello, main, system, cin, cout, … Ø Keywords(reserved names): int, double, if, while, return, … Ø Symbols: =, *, /, +, -, %, ==, !=, //, ++, --, … Ø Delimiters: pairs of parentheses: (), braces: {}, square brackets: [], single quotes, double quotes, /* */ Ø Constant: 5, 3. 1416, ‘A’, “I like Java”, … Ø Comments 10

Compiler directives Keywords Identifiers //hello. cpp #include <iostream> using namespace std; int main() { cout << ("Hello, C++ freaks!n"); system("PAUSE"); return 0; } //main Comments String constant 11

Names (Identifiers) Ø A C++ program consists of many names Ø A valid name begins with a letter, followed by any number of letters or digits. Ø Letters: A, B, …, Z, a, b, …, z, _ Ø Digits: 0, 1, …, 9 Let underscore be a letter Ø Case sensitive: abc is different from Abc Ø Avoid keywords Ø Valid names: A, a 2 c, HKU_CS, _2, _B, _ _A Ø Invalid names: 2 c, A B, A%B, -D, $A, new 12

Keywords (Reserved Names) A set of names with pre-defined meanings asm auto bool break case catch char class const_cast continue default delete do double dynamic_cast else enum explicit extern false float for friend goto if inline int log long mutable namespace new operator private protected public register reinterpret_cast return short signed sizeof static_case struct switch template this throw true try typedef typeid typename union unsigned using virtual void volatile wchar_t while 13

1. What is the exact quantity of 1 mega? 2. cpu is the acronym of _____________. 3. Which of the following are valid names? (i) 5 E 5 (ii) Class (iii) 1 A (iv) $_$_$ (v) int (vi) No-Way (vii) Bad_taste 14

Data type Ø A program processes data Ø Every datum belongs to a type Ø Primitive types in C++: int, double, bool, char Ø A constant belongs to a type. E. g. , 5 is an int constant Ø In the version of C++ we use, ØAn int value occupies 4 bytes ØA double value occupies 8 bytes ØA bool value of true or false occupies 1 byte ØA char value occupies 1 bytes 15

E. g. , ‘A’ is represented as 41, in hexadecimal digits; ‘B’ as 42, ‘a’ as 61, ‘ 0’ as 30. The first 128 characters are equivalent to the 7 -bit ASCII character set. Constants Ø A constant is an item representing an unchanged value in a program. Eg, ØInteger (int) constants: -35, 112, 0 ØReal (double) constants: 0. 0, 3. 1416, -100. 0 ØCharacter (char) constants: ‘A’, ‘e’ ØBoolean (bool) constants: true, false 16 ØString constants: “I love C++”

Ø A string constant is a sequence of characters, e. g. , “Who am I? ” is a String constant containing 9 characters. Ø Note the difference between Ø 9, an int constant, Ø‘ 9’, a char constant, and Ø“ 9”, a string constant of one character. 17

Ø 5 is an ____ constant (occupies ___ bytes) Ø 5. 0 is a _______ constant (occupies ___ bytes) Ø ‘ 5’ is a _____ constant (occupies ___ bytes) Ø “ 5” is a _______ constant of ____ character Ø true is a ____ constant (occupies ___ byte) Ø False is ______ constant Ø “true” is a ____ constant 18

Variables Ø A variable is a symbolic name given to a sequence of RAM cells for storing a value, e. g. , 5 Ø An int variable represents ___ bytes that store an int value Ø A double variable represents ___ bytes that store a double value Ø A char variable represents ___ bytes that store a char value Ø A bool variable represents ___ byte that store a bool value 19

The concept of variables is utmost important! 20

Ø Variable declaration: to specify the type of data that will be stored in a variable cell. E. g. , . . . int f 2 c; f 2 c, int. . . double x; . . . x, double Ø Type compatibility: Only a value of the same type is allowed to be put into the cell represented by a variable Ø A variable must be declared before its use 21

Ø Symbolic constants const double PI = 3. 141592653589793; const double LIGHT_VELOCITY = 186000; const int MAX_ENROLMENT = 60; The modifier const indicates that the value of a variable cannot be changed during execution. It is a good programming practice to define constants as symbolic constants with meaningful names. 22

Naming conventions Ø A variable or function name consists of lowercase letters. E. g. , count, fahr, c 2 f, f 2 c Ø The name of a symbolic constant consists of only capital letters. E. g. , PI, LIGHT_VELOCITY Ø If a name consists of multiple words, they are joined together with underscores. E. g. , hello_world, button_clicked, hong_kong_university Ø All names shall be meaningful 23

Assignment statements Ø An assignment statement is an instruction that asks the cpu to store a value in the cells represented by a variable. E. g. , count = 5; means “put the value 5 in the cells represented by count ” Ø When a variable is reassigned later, the previous value in the cells is overwritten, e. g, count = 5; . . . count = 0; //The new value in count is 0 Ø When a variable appears on the right hand side of the ‘=‘ in an assignment, it represents the value stored in its cells. E. g. , k = count; means “get the value stored in count and put it in the cells represented by k ”. 24

Operators and expressions Ø An operator specifies an operation for the cpu to carry out, E. g. , x + y means: get the value of x, get the value of y, add the two values; Ø In this example, x and y are the operands Ø An expression is a series of operations specified using constants, variables and operators. E. g. , x + y, count + 1, a - b - c, a * (b - c) Ø The value of an expression is the resulting value after evaluation 25

Ø In general, Ø <expression> <const> Eg, 3, 4. 5 Ø <expression> <variable> Eg, i, count Ø <expression> <op> expression> Eg, i + 3 * b Ø <assignment> <variable> = <expression>; Eg, a = i + 3; a = a + 1; 26

Ø An operator associates with a data type. Ø An integer addition adds two integers and the sum is an integer, eg, 3 + 5 gives 8, 7 / 2 gives 3 Ø A double addition adds two real numbers and the sum is a double, eg, 3. 2 + 5. 0 gives 8. 2, 7. 0 / 2. 0 gives 3. 5 Ø Integer addition and double addition are two different operations but are represented by the same symbol + for convenience (Overloading of the operator +). 27

Ø Rules that determine whether a + means an integer addition or a double addition Ø If both operands are integers, it means integer addition Ø If both operands are doubles, it means double addition Ø If one is integer and the other is double, it means double addition. The integer operand will be automatically converted into the equivalent double value before addition. Eg, 3 + 5. 1 3. 0 + 5. 1 = 8. 1 28

Ø Similarly, a slash, ‘/’, may mean integer division or double division. These two are totally different operations. The same rules are applied to determine whether a ‘/’ means the former or the latter 7/3 //Integer division, result is 2 7/ 3. 0 //Double division, result is 2. 333. . . Ø In the later case, 7 is first casted (converted) into 7. 0 before the division. The result is 2. 333333… of type double. (The conversion is automatic in this case. ) Ø The same is true for other arithmetic and relational operators, e. g. , -, *, <, <=, . . . 29

Type conversions (casting) Ø In general, the assignment statement <variable> < expression>; asks the cpu to evaluate the <expression> and stores the result in the cells represented by the <variable>. If the type of the result is different from that of the variable, a type conversion (casting) is conducted. E. g. , int x; double y; //from int to double, casting is automatic y = 7 / 3; x = 7. 0 / 3; //from double to int, explicit casting is needed x = static_cast(int) (7. 0 / 3); //Alright. // static_cast(int) changes the result from double to int 30

Simple IF statements Ø In daily life, we often do (or do not do) something, depending on a condition. Eg, ØIf it rains, bring an umbrella. ØIf typhoon signal No. 8 is hoisted, go home. ØIf she knows C++, date her. Ø We can attach a condition to a statement. If the condition is true, execute the statement. Otherwise, skip to next statement. 31

Ø Example if (work_hour > 40) { over_time_hour = work_hour - 40; over_time_salary = over_time_hour * 45. 0; } true Work_hour > 40 Over_time_hour = work_hour - 40; false Over_time_salary = over_time_hour * 45. 0; The assignment statements ( then-part ) will only be 32 executed when work_hour > 40

Simple While loops Ø In daily life, we often do something repeatedly. Eg, we brush our teeth everyday. We construct a building floor by floor in the same way. Ø Moreover, we do something repeatedly as long as a certain condition is satisfied. Eg, we breathe while we are alive. We construct a building floor by floor while the roof is not yet reached. Ø In computation, we frequently execute a segment of code repeatedly while a condition (while-condition) is satisfied. 33

Ø To find the smallest integer that is a power of two (2 k) and larger than 10 Idea: Compute 21, 22, 23, … one by one while the result is less than or equal to 10 k = 1; while (k <= 10) { k = 2 * k; } k k 10 Before 1 true After 1 st round 2 true After 2 nd round 4 true After 3 rd round 8 true After 4 th round 16 false Iteration k = 1; false k <= 10 true k = 2 * k; 34

Comments Ø Texts that are used to explain a program to human readers. They are entirely ignored by a computer during execution. Ø One-line comments A text starts from // to end_of_line. E. g. , a = b + c; //This part is a 1 -line comment Ø Multiple-line comments A text delimited by /* and */, E. g. , /* Starting lines … A multiple-line comment */ Ø Comments may be placed anywhere except in the middle of a number or a word. 35
- Slides: 35