Introduction to Computer Science p Instructor n p


















































- Slides: 50

Introduction to Computer Science p Instructor: n p Textbook: n p Dr. Quincy Wu (solomon@mail. ncnu. edu. tw) Ivor Horton, "Ivor Horton's Beginning Visual C++ 2013", Wrox (May 12, 2013). Evaluation: Grading n n Quiz (30%) Homework (10%) Midterm Exam (30%) Final Exam (30%)

Programming Environment p Visual Studio 2017 Community n n p https: //imagine. microsoft. com/enus/Catalog/Product/530 BASIC, C++, FORTRAN, Fox. Pro, Java, … Choose "Desktop development with C++" - "Visual C++ MFC for x 86 and x 64". 13

A Few Suggestions Take notes p Think about it. p Practice again. p Teach it. p Identify your weakness and try to improve. p

Chapter 2 Data, Variables, and Calculations 15

Ex 2_01 p Start a new Win 32 Console Project n n n p Ctrl+Shift+N Choose Empty project Right-click Source Files and Add > New Item Choose category Code and template C++ file (. cpp). 22

Add New Item 23

<F 7> to Build 24

Syntax of C Language // Ex 2_00. cpp // Simple calculation #include <iostream> Comments begin with // int main() { int a, b, c; Variable declaration a = 10; b = 20; c = a + b; std: : cout << "The summation a + b = "; std: : cout << c; std: : cout << std: : endl; } return 0; A statement block is enclosed by braces. Each statement ends with a semicolon. End-of-Line Whitespace (P. 35) 25

main( ) p p p Every standard C++ program contains the function main(). A Program in C++ consists of one or more functions. A function is simply a self-contained block of code with a unique name. n p You can invoke a function by its name. The principal advantage of having a program broken up into functions is that you can write and test each piece separately. n Re-use 29

The IPO Structure of a Program int main( ) { input( ); process( ); output( ); return 0; } 30

Naming Variables p Variable names can include the letters AZ, a-z, the digits 0 -9, and the underscore character (_). n n Variable names cannot begin with digits. Avoid naming a variable name to begin with an underscore (_this, _that), because it may conflict with standard system variables. Variable names are case-sensitive. p Convention in C++ p n n Classes names begin with a capital letter. Variable names begin with a lowercase letter. 31

Naming Variables (2) p In Visual C++, variable names can be arbitrarily long. n n p However, not all compilers support such long names. n p number_of_students average_score It’s a good idea to limit names to a maximum of 31 characters. Illegal variable names: n n 8_Ball, 7 UP Hash!, Mary-Ann 32

Q: Why do we need to declare variables? A: To reserve memory spaces. Declaring Variables p int value; n p int i, j, k; n n p This declares a variable with the name value that can store integers. A single declaration can specify the names of several variables. However, it is better to declare each variable in a single line. (Why? See. P. 39) int value = 10; n When you declare a variable, you can also assign an initial value to it. 33

Basic Input/Output Operations p Input from the keyboard n p cin >> num 1 >> num 2; Output to the command Line n n cout << num 1 << num 2; cout << num 1 << ' ' << num 2; 34

Exercise: In which year were you born? Input: In which year were you born? p Output: Your age. p Relationship: age = 2019 - year p p The program may run as follows: n n In which year were you born? 2001 You are 18 years old. 35

Exercise: Chickens and Rabbits 36

Bits and Bytes p Bit n The smallest unit of storage p p n A bit can store just 0 or 1. p p Power on/off Magnetic north/south Too small to be useful. Byte n One byte = a group of 8 bits p n n e. g. , 01000001 One byte can store one character, e. g. , ‘A’, ‘k’, or ‘? ’ One byte can also store an integer, e. g. , 0, 15, or 64 37

Kilobyte vs. Kibibyte Value Metric Value IEC 1000 k. B kilobyte 1024 Ki. B kibibyte 10002 MB megabyte 10242 Mi. B mebibyte 10003 GB gigabyte 10243 Gi. B gibibyte 10004 TB terabyte 10244 Ti. B tebibyte 10005 PB petabyte 10245 Pi. B pebibyte 10006 EB exabyte 10246 Ei. B exbibyte 10007 ZB zettabyte 10247 Zi. B zebibyte 10008 YB yottabyte 10248 Yi. B yobibyte 38

Integer Types & Character Types p Integer Types n n n int short long p p // 4 bytes // 2 bytes // 4 bytes, same as int in Visual C++ 2013 However, in a 64 -bit host (e. g. STU. ipv 6. club. tw), sizeof(long) is 8 bytes. § So this may lead to expected results if you run the same program on different platforms. n p long // 8 bytes Character Data Types n char letter = 'A'; p p p // 1 byte Single quote, not double quote (") The ASCII code of the character is stored in that byte. Therefore, it is equivalent to char letter = 65; 39

Integer Type Modifier p Examples: n n signed int; signed short; p n Range: 0 ~ 65535 signed char; p n Range: -32768 ~ 32767 unsigned short; p n // equivalent to int // equivalent to short Range: -128 ~ 127 unsigned char; p Range: 0 ~ 255 40

Boolean Type p Examples: n n p bool test. Result; bool color. Is. Red = true; In old C language, there is no bool data type. n Variables of type int were used to represent logical values. Zero for false; non-zero for true. p Symbols TRUE and FALSE are defined for this purpose. p Note that TRUE and FALSE are not C++ keywords. p Don’t confuse true with TRUE. p 41

Floating-Point Type p A floating-point constant contains a decimal point, or an exponent, or both. n n p 112. 5 1. 125 E 2 Examples: n double inch_to_cm = 2. 54; p 8 bytes § 1 bit sign § 11 bit exponent § 52 bit mantissa n float pi = 3. 14159 f; p // P. 44 4 bytes § 1 bit sign § 8 bit exponent § 23 bit mantissa 42

The const Modifier p const float inch_to_cm = 2. 54 f; n n If you accidentally wrote an incorrect statement which altered the value of inch_to_cm, the compiler will fail and complain. Avoid using magic numbers like 2. 54 in your program when the meaning is not obvious. Declare a constant for it. All the above data types can have const modifiers. p Constant Expressions p n const float foot_to_cm = 12 * inch_to_cm; 44

Exercise: sizeof Operator 45

The Using Decleration // Ex 2_00. cpp // Simple calculation #include <iostream> int main() { int a, b, c; a = 10; b = 20; c = a + b; // Ex 2_00 a. cpp // Simple calculation #include <iostream> using std: : cout; using std: : endl; int main() { int a, b, c; a = 10; b = 20; c = a + b; std: : cout << "a + b = "; std: : cout << c; std: : cout << std: : endl; } cout << "a + b = "; cout << c; cout << endl; return 0; } return 0; 46

#include <iomanip> #include <iostream> #include <iomanip> using std: : cout; using std: : endl; using std: : setw; int main() { int num 1 = 10; int num 2 = 200; cout << num 1 << cout << setw(6) return 0; } 10200 10 200 num 2 << endl; ' ' << num 2 << endl; << num 1 << setw(6) << num 2 << endl; << num 2 << setw(6) << num 1 << endl; 200 10 47

Escape Sequences p An escape sequence starts with a backslash character, . n n p cout << endl << "This is a book. "; cout << endl << "t. This is a book. "; Some useful escape sequences: n n n n a n b t ' " \ alert with a beep newline backspace tab single quote double quote backslash 48

Assignment Statement p variable = expression ; n n n p // the quotient is an integer // remainder Repeated assignment n p c = a + b; q = 27 / 4; r = 27 % 4; a = b = 2; Modifying a variable n n n d = a + b / c; // d = a + (b / c) count = count + 5; count += 5; // shorthand notation count *= 5; // count = count * 5 a /= b + c; // a = a / (b + c) 49

Exercise: What Day is January 1 st 50

Increment Operators p p Frequently used in C++ The following statements have exactly the same effect: n n n p // shorthand // unary operator Prefix form: increment before the value is used. n n p count = count + 1; count +=1; ++count; int total, count = 1; total = ++count + 6; // count=2; total = 8 Postfix form: increment after the value is used. n n total = count++ + 6; total = 6 + count++; // total = 7; count=2 51

We may have a quiz like this p What would be the output of the following code: #include <iostream> using std: : cout; using std: : endl; int main() { int a = 10; int b = 20; cout << a++ + ++b << endl; return 0; } 52

Decrement Operators p Unary operator to decrease the integer variable by 1. n n p total = --count + 6; total = 6 + count--; Both increment and decrement operators are useful in loops, as we shall see in Chapter 3. 53

Comma Operator p Specify several expressions in an assignment n n n p p int num 1; int num 2; int num 3; int num 4; num 4 = (num 1=10, num 2=20, num 3=30); Operator Precedence (see P. 61~P. 62) It is a good idea to insert parentheses to make sure. 54

Casting p The conversion of a value from one type to another n Implicit type conversion p p p int n; float a = 7. 0; float b = 2. 0; float c = a / b; n = c; § The floating-point value will be rounded down to the nearest integer (3) § The compiler will issue a warning. n Explicit cast p n = static_cast<int> ( c ); § The compiler assumes you know what you are doing and will not issue a warning. n Old-style cast p (not recommended) n = (int) c ; 55

Exercise: Volume & Area Input: radius p Output: The volume and surface area of a sphere. p Relationship: p n n p V = 4/3 π r 3 A = 4 π r 2 Hint: You may define a constant pi = 3. 14159. 56

HW: Solving Linear Equations p 57

HW (cont. ) p Sample input n n p 2. 0 1. 0 7. 0 -1. 0 2. 0 9. 0 1. 0 5. 0 1. 0 -1. 0 4. 0 Sample output n n x=1, y=5 x = 4. 5 , y = 0. 5 58

Bitwise Operators p The bitwise operators are useful in programming hardware devices. & | ^ ~ >> << p AND OR exclusive OR NOT shift right shift left You may pack a set of on-off flags into a single variable. n 0101 1100 59

Examples of Bitwise Operators p Bitwise AND n n n p char letter = 0 x 41; // 0100 0001 char mask = 0 x 0 F; // 0000 1111 letter = letter & mask; Bitwise Shift Operators n n n char j = 2; // j <<= 1; // j >>= 2; // j = -104; // j >>= 2; // 0000 1001 1110 0010 0100 0001 1000 0110 (=? ) 60

Storage Duration and Scope p Duration n p Automatic storage duration Static storage duration Dynamic storage duration (Chapter 4) Scope n The part of your program over which the variable name is valid. 61

Automatic Variables p Automatic variables have local scope (block scope). n n n Every time the block of statements containing a declaration for an automatic variable is executed, the variable is created anew. If you specified an initial value for the automatic variable, it will be reinitialized each time it is created. When an automatic variable dies, its memory on the stack will be freed for used by other automatic variables. 62

Ex 2_07. cpp in P. 73 p p p From the viewpoint of the outer block, the inner block just behaves like a single statement. The inner block also declares a variable named count 1, so the variable count 1 declared in the outer block becomes hidden now. Other variables (count 3) declared at the beginning of the outer scope are accessible from within the inner scope. After the brace ending the inner scope, count 2 and the inner count 1 cease to exist. Try to uncomment the line // cout << count 2 << endl; to get an error. 63

Global Variables declared outside of all blocks are called global variables and have global namespace scope. p Global variables have static storage duration by default. It will exist from the start of execution of the program, until execution of the program ends. p n n If you do not specify an initial value for a global variable, it will be initialized with 0 by default. On the contrary, automatic variables will not be initialized by default. 64

Figure 2 -11 (P. 76) p An example that the lifetime and scope may be different (value 1). 65

Namespaces p Namespace is a mechanism to prevent accidental naming clash. n n p The libraries supporting the CLR and Windows Forms use namespaces extensively. The ANSI C++ standard library does, too. Every non-local variable or function must be qualified. // Ex 2_09 a. cpp #include <iostream> int value = 0; int main() { std: : cout << "enter an integer: "; std: : cin >> value; std: : cout << "n. You enterd " << value << std: : endl; return 0; } global namespace scope Note the absence of using declarations for cout and endl 67

using Directive p using namespace std; n n This imports all the names from the std namespace so that you don’t need to qualifying the name with prefix std: : in your program. However, this negates the reason for using a namespace. Only introduce the names that you use with “using declaration”: using std: : cout; p using std: : endl; p 68

Declaring a Namespace // Ex 2_09. cpp // Declaring a namespace #include <iostream> namespace my. Stuff { int value = 0; } int main() { int value std: : cout std: : cin std: : cout = 925; << "enter an integer: "; >> my. Stuff: : value; << "n. You entered " << my. Stuff: : value << std: : endl; std: : cout << "The local variable value = " << value << std: : endl; return 0; } 69

using Directive // Ex 2_10. cpp // using a using directive #include <iostream> namespace my. Stuff { int value = 0; } using namespace my. Stuff; int main() { std: : cout << "enter an integer: "; std: : cin >> value; std: : cout << "n. You entered " << value << std: : endl; return 0; } // my. Stuff: : value 70

using Declaration // Ex 2_10 a. cpp // using a using declaration #include <iostream> namespace my. Stuff { int value = 0; } using my. Stuff: : value; // only import variables that you need int main() { std: : cout << "enter an integer: "; std: : cin >> value; std: : cout << "n. You entered " << value << std: : endl; return 0; } 71

Exercise p P. 87. n Exercise 1, 2, 3, 4, 5. You don’t need to upload, but we shall have a quiz later. p Also try to run the sample code introduced in this chapter, to get a feeling about the syntax of C++ language. p 72