2Elementary C++ Programming

The chapter begins with a brief look at the history of C++ the language and its characteristics. Then we look at the basic elements that construct a C++ statement – character sets, keywords, identifiers, operators, etc. Program design mainly includes data structure design and algorithm design. Data types, data type conversion, and simple data input/ output are the basic knowledge elements of data. The chapter introduces basic C++ data types and user-defined data types. Algorithms consist of a series of control structures. The sequential, case, and loop structures described in this chapter are the most fundamental control structures in program design, and they are also the basis of complex algorithms.

2.1An Overview of C++ Language

2.1.1Origins of C++

C++ originates from the C language. Thus, to understand C++ better, the history of the C language should be reviewed first. The C languagewas first realized on a DEC PDP-11 computer in 1972. Dennis Ritchie, working in Bell Laboratory, created it based on the B language. After that, continuous improvements have been made and nowadays the comparatively popular C languages are based on ANSI C.

The C language has many advantages, such as its simplicity and agility, its abundant operators and data structures, its structured controlling statements, and its high efficiency when executing programs. It combines the advantages of both high-level languages and assembly language: compared with other high-level languages, the C language can access physical address directly; while compared with assembly language, it has better readability and portability. Because of all these features, the C language has been widely used by numerous programmers, and there are many C library codes and developing environments.

However, since the C language is a procedure-oriented programming language, like other procedure-oriented languages, it cannot meet the needs of software development that uses object-oriented methods. C++ was then created from C to support object-oriented programming. It is a general-purpose language. It was created by Bjarne Stroustrup, a doctor at AT&T Bell Labs, in 1980.

Since the primary objective in creating the C++ language was to make it a better C, C++ has successfully solved all the problems in C. Another important goal of C++ was to support object-oriented programming, and thus class was introduced. The initial name for C++ was “C with Class”, and later in 1983 it was formally renamed as C++. The standardization of C++ began in 1989 and an ANSI C++ standardization draft was made in 1994. In the following years, continuous improvements were made before it was approved by the ISO (International Standardization Organization) as an international standard in November, 1998, known then as the current C++.

2.1.2Characteristics of C++

The C++ language has two main characteristics: it is fully compatible with C and it supports object-oriented methods.

First of all, C++ is indeed a better C. It keeps some features of C, such as C’s simplicity, high efficiency, and closeness with assembly language. Furthermore, it reforms and expands the type system of C, making it safer and its compiling system more capable of detecting type errors than C.

As C++ is compatible with C, many C codes can be used in C++ without any modification. Many library functions and utility software written in C can be used in C++. In addition, the widespread use of the C language promotes the spread of both C++ and object-oriented techniques.

However, from another perspective, C++’s compatibility makes it not a pure object-oriented language. It supports both procedure-oriented programming and object-oriented programming.

The most meaningful feature of C++ is that it supports object-oriented programming. Although its compatibility with C makes it have dual characteristics, conceptually speaking it is totally different from C. Thus we had better write C++ with an object-oriented way of thinking.

If you already have some procedure-oriented programming experience, we suggest that you pay more attention to the object-oriented feature of C++ and less attention to its similar parts with C, for C and other procedure-oriented high-level programming languages are similar in design methods.

However, beginner programmers cannot overlook the compatible parts of C++ with C, although they are not the main content of C++. This is because that many elements such as data types, controlling structures of algorithms, functions, etc. are not only basic components of procedure-oriented programming, but also fundamental knowledge for object-oriented programming. In object-oriented programming, objects are the basic units for a program, while their static attributes always need to be represented by certain data type, and their dynamic attributes need to be realized by their member functions whose implements are, after all, the design of algorithms.

2.1.3C++ Programming Examples

The following is an example of C++ programming. Since the characteristics of object-oriented programming have not been discussed, Example 2.1 is only a procedure-oriented program, by which we can find out what a computer program looks like and how to use it to control the operations of a computer.

Example 2.1: A simple C++ program.

Here, main is the main function name, and its function body is enclosed in a pair of braces {}. Function is the smallest functional unit in C++ programs. In a C++ program there must be one and only one function named main(), which denotes the starting point of the execution of the program. The int before main() is the type of the return value of the function (the return value of function will be detailed in Chapter 3). Inside the function body there are statements, and each of them is ended by a semicolon (;). cout is an output stream object. It is a predefined object in the C++ system and contains many useful output functions. Output operations are implemented by the operator “<<”, whose function is to direct the character string inside the following double quotation marks to the standard output device (monitor). Chapter 9 will detail the output stream and here readers just need to know that “cout<<” is used to achieve outputs.

The following words in this program

tell the C++ compiler to read the source codes in the iostream file into this text file when it preprocesses the program. Here #include is called a compiling directive. The file iostream declares the information needed by the input and output operations of a program, and also the information about cout and <<. Files of this kind are referred to as header files, for they are always embedded at the beginning of a program. If some system functions are used in a C++ program, relative header files must be included.

The expression using namespace is a directive concerning namespace whose concept will be covered in Chapter 5. Beginner programmers are only required to add the following statement after including the iostream file:

When we finish writing a program text, we need to store it as a . cpp file, which is called a C++ source file. It will generate an executable file suffixed with .exe after compiling and linking through the compiling system. All the examples used in this book are developed in the integrated environment of Microsoft Visual C++ 6.0. For more information about developing programs in this environment, please refer to matching books of exercises and experiment guidance.

Example 2.1 has an output on the screen as follows:

Header files that the C++ compiler system provides can be divided into two categories. One is header files from the standard C++ libraries, which have no suffixes, such as <iostream> used in the above example; the other follows the C language style and has a suffix “.h”, such as <iostream.h>. Examples and exercises in this book use header files from standard C++ libraries (i.e., without any suffix). However, some other textbooks and examinations may still use the latter kind of header files with a suffix “.h”.

2.1.4Character Set

The character set is the basic element of the C++ language. When programming with C++, all the components are made up of characters except for character data. Character set of C++ is made up of the following characters:

Alphabetic characters: A~Z, a~z

Numerical characters: 0~9

Special characters:

2.1.5Lexical Tokens

The lexical token is the smallest lexical unit. Here we will introduce the keywords, identifiers, characters, operators, separators, and blanks in C++.

1.Keywords

A keyword in C++ is a word that is predefined and reserved for some specific usage. C++ now has the following keywords:

Further introduction of their meanings and usages will be covered later in this book.

2.Identifiers

Identifiers are defined by programmers. They are used to name entities in the program body such as functions, variables, classes, and objects. Rules to make up a C++ identifier are as follows:

Start with upper cases, lower cases or underscore (_).

Must consist of upper cases, lower cases, underscore (_) or numbers (0~9).

Upper cases and lower cases stand for different identifiers.

Should not be C++ keywords.

For example, Rectangle, Draw_line and _No1 are all legal identifiers, while NO.1 and 1st are illegal identifiers.

3.Literal Constants

Literal constants are directly represented by symbols in programs, which include numbers, characters, alphabetic strings, and Boolean literals. They are to be covered in the next section.

4.Operators

Operators are symbols used to realize operations, such as +, −, *, /, and ... Details of operators are to be covered in the second section of this chapter and the following chapters.

5.Separators

Separators are used to detach lexical tokens or program bodies. C++ has the following separators:

These separators stand for no actual operation and are only used to construct programs. More details will be covered later.

6.Blanks

A program body is divided into lexical tokens and blanks during its lexical analysis in the compiling phase. Blank is the general name for space, tab (generated by pressing TAB), line break (generated by pressing ENTER), or comment.

Blanks are used to identify the starting and ending positions of lexical marks. But for this function, all the other blanks are omitted. Thus you do not need to write programs strictly line by line: anywhere blanks are left, a new line can be made. For example, the following three ways perform, in effect, the same function:

However, it is strongly recommended to write programs with clearness and readability. This is because programs not only need to be executed by machines, but also need to be revised and maintained by programmers.

Comments in a program are used to explain and interpret the program to improve its readability. When the compiling system compiles the source program, it first strips the comments. Thus comments have no effect on the realization of a program’s functions. In addition, since they are stripped by the compiler before code generation, they will not increase the size of the final executable program. Comments, if used properly, can make a program more readable.

There are two ways to add comments in C++. One follows the C language, using “/*” and “*/” to enclose comments just as follows:

Here all the symbols between “/*” and “*/” are to be recognized as comments.

The other way uses “//” to delimit a single-line comment. Starting from “//” and ending until the finishing point of that line, all the characters in between are viewed as comments. For example,

2.2Basic Data Types and Expressions

Data are the objects programs process. They can be classified according to their characteristics. For example, in mathematics there are concepts like integers, real numbers, etc.; in daily life we need character strings to denote a person’s names and addresses; the answers of some questions can only be “yes” or “no” (i.e., “true” or “false” in logic). Different types of data have different processing methods. For example, both integers and real numbers can participate in arithmetical operations, while real numbers differ from integers in that they have to retain a certain part of decimal fractions; character strings can be concatenated; logical data can participate in logical operations such as “and”, “or”, “non-”, etc.

We write programs to solve practical questions in the objective world. Therefore, high-level languages provide us with a wealth of data types and operations. C++ data types are divided into two categories: basic data types and user-defined data types. Basic data types are predefined within the C++ compiler system. Wewill first introduce the basic data type in this section.

2.2.1Basic Data Types

Basic C++ data types are shown in Table 2.1.

We can see from Table 2.1 that basic C++ data types include bool (Boolean type), char (character type), int (integer type), float (floating-point type, representing real numbers), and double (double-precision floating-point type, or double-precision type). Apart from bool these data types can be classified into two main categories: integer and floating-point. char is an integer type essentially. It is a one-length integer, so usually we use the ASCII code to store characters. Keywords signed, unsigned, short, and long are called qualifiers.

When short is used to qualify int, short int denotes short integers, occupying 2 bytes. int can be omitted here, so the one listed in Table 2.1 is written as short instead of short int. long can be used to qualify int and double. When long qualifies int, long int denotes long integers, occupying 4 bytes. int here also can be omitted. From Table 2.1 we can see that int and long have the same length, so why do we need to provide two different data types in the syntax? This is because the number of bytes that int needs may not be the same in different systems, and we only listed the situation under the VC++6.0 compiler environment (also the situation in most compiler environments).

Tab. 2.1: Basic C++ Data Types.

Name Length (bytes) Range
bool 1 false, true
char(signed char) 1 −128 ∼ 127
unsigned char 1 0 ∼ 255
short(signed short) 2 −32768 ∼ 32767
unsigned short 2 0 ∼ 65535
int(signed int) 4 −2147483648 ∼ 2147483647
unsigned int 4 0 ∼ 4294967295
long(signed long) 4 −2147483648 ∼ 2147483647
unsigned long 4 0 ∼ 4294967295
float 4 3.4 × 10−38 ∼ 3.4 × 1038
double 8 1.7 × 10−308 ∼ 1.7 × 10308
long double 8 1.7 × 10−308 ∼ 1.7 × 10308

The numbers of bytes that short and long need are both fixed in any compiler system that supports standard C++. Therefore, if we want to write a program with good portability, we should declare the integer type as short or long instead of int.

signed and unsigned can be used to qualify char type and int type (including long int). signed indicates signed numbers, while unsigned indicates unsigned numbers. Signed integers are stored in computers in the two’s complement form, and its most significant bit is the sign bit, where “0” denotes “positive” and “1” denotes “negative”. Unsigned integers can only represent positive numbers, which are stored in the absolute form. Both char type and int type (including long int) in default (without qualification) are signed.

The value of bool (Boolean, also known as logical type) data can only be false or true. The number of bytes that the bool data needs may not be the same in different compiler systems. In the VC++6.0 compiler environment the bool type has only 1 byte.

Data that programs process can be divided into different types, while in each type the data can be constants or variables. We will detail all kinds of basic data types in the next section.

2.2.2Constants

The value of a constant is immutable during the entire process of a program, i.e., a constant directly uses symbols (literals) to express its value. For example: 12, 3.5, and ‘A’ are all constants.

1.Integer Constants

Integer constants are integers in the form of literals. They include positive integers, negative integers, and zero. Integer constants can be represented in the decimal, octal, or hexadecimal form.

The general form of a decimal integer constant is the same as that in mathematics:

[±]severalnumbersfrom0to9,

namely, a sign followed by several numbers from 0 to 9. Note that the numerical part cannot start with 0, and the positive sign in front of a positive number can be omitted.

The numerical part of an octal integer constant starts with 0, and its general form is:

[±]0severalnumbersfrom0 to 7

The numerical part of a hexadecimal integer constant starts with 0x, and its general form is:

[±] 0x several numbers from 0 to 9 and/ or letters from A to F (case insensitive)

Integer constants can use the suffix letter L (or l) to denote a long integer type, the suffix letter U (or u) to denote an unsigned type, or the suffix letters of both L and U (case insensitive) to denote an unsigned long integer type.

For example: 123, 0123, and -0x5af are all legal constant forms.

2.Real Constants

Real constants are real numbers in the form of literals, and they have two representation forms: the general form and index form.

General form: for example: 12.5, −12.5 and so on.

Index form: for example, 0.345E+2 denotes 0.345 × 102 and −34.4E−3 denotes −34.4 × 103. Here the letter E is case insensitive. When using the index form to denote a real number, its integral part or the decimal fraction can be omitted, although they cannot be both omitted. For example: .123E−1, 12.E 2, and 1.E−3 are all correct forms, but E−3 is wrong.

The default type of real constants is double, and the suffix F (or f) can convert a real constant into a float type. For example: 12.3f.

3.Character Constants

A character constant is one character enclosed by single quotes, such as: ‘a’, ‘D’, ‘?’, or ‘$’.

In addition, there are some characters that cannot be displayed or input by keyboard, such as ring, newline, tab, enter, etc. How does one write these characters into a program? C++ provides a set of escape sequences to represent these characters. The predefined escape sequences in C++ and their meanings are shown in Table 2.2.

Both general characters and nonprintable characters can be represented by octal or hexadecimal ASCII codes with the form as:

nnn denotes a sequence of at most three octal or hexadecimal numbers.

Tab. 2.2: C++ Predefined Escape Characters.

Character constant form ASCII code (hexadecimal) Meaning
a 07 Ring
0A Newline
09 Horizontal tab
v 0B Vertical tab
 08 Backspace
0D Carriage Return
\ 5C Character “”
22 Double quote
27 Single quote
Fig. 2.1: Memory presentation of string and character.

For example, the hexadecimal ASCII code of ‘a’ is 61, so ‘a’ also can be written as ‘x61.’

Since single quotes are the boundary of a character, a single quote itself needs to be represented using escape sequence ‘’.’

Character data is stored in ASCII code in memory. Each character needs 1 byte, using the lowest 7 binary bits of the byte.

4.String Constants

String is short for string constants, using a pair of double quotes to enclose the character sequence. For example: “abcd”, “China”, and “This is a string”. are all string constants. Since double quotes are the boundary of characters, a double quote itself needs to be represented using the escape sequence. For example:

means:

Please enter “Yes” or “No”

A string is different from a character. String is stored in memory as a sequence of characters in the order of the characters it owns. Each character takes up one byte, and at the end of the string ‘’ should be added as an end mark. Figure 2.1 is an example. From the figure we can find out that string “a” and character ‘a’ are not the same.

5.Bool Constants

There are only two bool constants: false and true.

2.2.3Variables

Variables have values that can change during the process of a program, and they need names to be identified.

1.Declaration and Definition of Variables

Just like constants, variables have various data types. We have to first declare the type and name of a variable before using it. Variables’ names are also identifiers; thus to name a variable, we should obey the rules of making up identifiers, which was introduced in the first section of this chapter. You can declare a number of variables with the same data type in one statement. The form of variable declaration statements is as below:

For example, the following two statements declare two int variables and three float variables:

The declaration of a variable only tells the compiler the identifier-related information of the variable for the compiler to “know” the identifier, although it does not necessarily cause the allocation of memory. Defining a variable, on the other hand, means to allocate memory space for the variable to store data of the corresponding type. The variable’s name is the name of its memory location. In C++ programs, defining a variable equals declaring the variable in most cases, and the definition is given when the variable is declared. The exception occurs when declaring external variables. We will introduce external variables in Chapter 5. We can initialize a variable while defining it, which is essentially initializing its memory location. For example:

There is another form of initialization when defining a variable, such as:

inta(3);

Note that although there are string constants in C++, there are no string variables. Then what type of variables should be used to store strings? In Chapter 6 wewill introduce how to store strings using character arrays.

2.Storage Types of Variables

Besides data types, variables also have storage types. Storage types determine how to store variables:

auto storage type: a stack allocated memory space. It is a temporary storage, and the storage space can be overlapped by a number of variables multiple times.

register storage type: stored in general registers.

extern storage type: can be referred by all functions and procedures.

static storage type: stored at some fixed address in memory, and remains valid during the entire runtime.

For beginners, you can temporarily ignore storage types here. After studying the scope and visibility of variables in Chapter 5, you will get a deeper understanding of the storage types of variables.

2.2.4Symbol Constants

Besides using literals to denote constants directly, we can also name a constant, which is called a symbol constant. Just like variables, symbol constants must be declared before they are used. The form of constant declaration statements is as follows:

For example, we can declare a symbol constant to represent π:

Note that symbol constants must be initialized when they are declared and they cannot be changed during the process. For example, the following statement is wrong:

Compared with using literals directly, giving a constant a meaningful name can improve the readability of the procedure. And if the procedure uses a literal constant (such as π = 3.14) several times, when the constant value needs to change (for example, π changes to 3.1416), multiple modifications may easily cause data inconsistency due to carelessness. By using symbol constants, since we only initialize a constant during its declaration, modifying it should be very easy and can thus avoid data inconsistency.

2.2.5Operators and Expressions

Up to now, we have known the characteristics and representations of data types in C++. Then how does one process data? When handling a computation, normally we should list the formula and then calculate its value. Using C++ language to solve these problems has the same procedure. Expressions are the basic units for calculations in programs.

Expressions can be interpreted as formulas used for calculations, which are made up of operators (such as: + − * /), operands (can be constants, variables, etc.) and brackets. Implementing the operation of an expression, we can get the result of the expression. For example: a+b, x/y are all expressions.

Now we use a more strict language to define expression. It does not matter if you cannot fully understand it right now. Expressions are ubiquitous in programs and we will soon detail various types of expressions. You can gradually understand it in further studies.

An expression can be defined as follows:

A constant or an identifier of a object is the simplest expression, and its value is the constant value or the value of the object.

The value of an expression can take part in other operations, i.e., it can be used as operands for other operators, which forms a more complex expression.

An expression inside a pair of brackets is still a expression, and its type and value are the same as the expression without brackets.

There are many operators in the C++ language, such as arithmetic operators, relational operators, logical operators, and so on. Some operators need two operands, and the form is as follows:

Such operators are called binary operators. Some other operators only need one operand, and they are called unary operators.

Operators have precedence and associativity. When an expression contains more than one operator, the operation with the operator of higher precedence should be done first, and then the operations with the operators of lower precedence. If there are several operators of same precedence in an expression, the operation order depends on the operator’s associativity. Associativity means the computation sequence where the operators on both sides of the operand have the same precedence. It can be from left to right or from right to left.

Now let us discuss the types of operators and expressions.

1.Arithmetic Operators and Arithmetic Expressions

Arithmetic operators in C++ include basic arithmetic operators, increments by one operator, and decrements by one operator. Expressions that are made up of arithmetic operators, operands, and brackets are called arithmetic expressions.

Basic arithmetic operators include: + (plus), − (minus or negative), * (multiply), / (divide), and % (modulus). “−” is a unitary operator when it represents a negative and is a dual operator in other cases. These basic arithmetic operators have the same meaning and precedence as their corresponding symbols in math. That is, multiplication and division have higher precedence compared with addition and subtraction, and operators associate left to right.

“%” is the modulus operator, can only be applied to integer operands. The result of the expression a%b is the remainder of a divided by b. The precedence of “%” is the same as “/”.

Note that when “/” is used to divide two integers, its result is the integral part of the quotient, and the fractional part is automatically discarded. Therefore, the result of the expression 1/2 is 0.

In addition, ++ (increment) and -- (decrement) are two operators that are easy to use and often efficient in C++. They both are unitary operators and have two forms: preposition and postposition. For example: i++, --j, and so on. Both forms will add (subtract) 1 to the operand, and then rewrite the location of the operand in memory. For example, if the original value of the variable i is 1, then after computing the expression i++, the result of the expression is 2 and the value of i will also change to 2. If the original value of j is 2, then after computing the expression –j, the result of the expression is 1 and the value of j will change to 1. However, when the result of increment and decrement are used to continue participating in other operations, the preposition and postposition are totally different. For example, if the value of i is 1, the result of the following two statements are not the same:

2.Assignment Operators and Assignment Expressions

C++ provides several assignment operators, in which the simplest one is “=”. Expressions with assignment operators are called assignment expressions. For example, n=n+5 is an assignment expression. An assignment expression assigns the value of the expression on the right side to the object on the left side. The type of the assignment expression is the same as the type of the object on the left side, and its result is the object’s value after the assignment. The assignment operators associate from right to left. See the following assignment expressions:

a=5 Expression value is 5.
a=b=c=5 Expression value is 5; a, b, c are 5. The expression operates from right to left: after c was updated to 5, the value of expression c=5 is 5, then b was updated to 5, and a was assigned to 5 at last.
a=5+(c=6) Expression value is 11, a is 11, c is 6.
a=(b=4)+(c=6) Expression value is 10, a is 10, b is 4, c is 6.
a=(b=10)/(c=2) Expression value is 5, a is 5, b is 10, c is 2.

Besides “=”, C++ also provides 10 kinds of compound assignment operators: +=, −=, *=, /=, %=, <<=, >>=, &=, ^=, and |=. The first five are compounded by assignment operators and arithmetic operators, while the rest are compounded by assignment operators and bitwise logical operators. Wewill talk about bitwise logical operators later. All the 10 kinds of compound assignment operators are binary operators, and they have the same precedence and associativity as “=”. Now we give an example of compound assignment operators:

a+=3 equivalent to a=a+3

x*=y+8 equivalent to x=x*(y+8)

a+=a-=a*a equivalent to a=a+(a=a-a*a)

3.Comma Operation and Comma Expression

In C++, the comma is also an operator, and its form of use is as below:

Solve expression 1 first, and then expression 2. The final result is the value of expression 2.

4.Logical Operators and Logical Expressions

We often need to judge a situation or analyze complex conditions logically when we solve problems. C++ provides relational operators used for comparison and judgment, and logical operators used for logical analysis.

Relational operators are kinds of simple logical operators, and their precedences are as below:

<(lessthan)<=(lessthanorequal)>(greaterthanorequal)sameprecedence(high)==(equal)!=(notequal)sameprecedence(low)

A relational expression connects two expressions using a relational operator. A relational expression is one of the simplest logical expressions. Its result type is bool, and the value can only be true or false.

For example: a>b, c<=a+b, x+y==3 are all relational expressions. When a is greater than b, the value of expression a>b is true, and otherwise the value is false. When c is less than or equal to a+b, the value of expression c<=a+b is true, otherwise the value is false. When the value of x+y is 3, expression x+y==3 is true: be careful that there are two equals here, so do not mistake it as an assignment operator “=”.

However, simple relation comparisons cannot meet the needs of programming, and we also need logical operators to connect simple relational expressions to form a more complex logical expression. The resulting type of logical expression is bool, and the value can only be true or false. The logical operators and their precedence in C++ are as below:

Tab. 2.3: Truth Table of Logical Operators.

“!” is an unitary operator, and its form of use is: ! operand. A nonoperation reverses the operand: if the value of operand a is true, then the value of expression !a is false; if the value of operand a is false, then the value of expression !a is true.

“&&” and “||” are both binary operators. “&&”gets the logical and of the two operands, and the operation result is true only when both of the operands are true; otherwise the result will be false. “||”gets the logical or of the two operands, and the operation result will be false only when both of the operands are false; otherwise the result will be true.

The operation rule of logical operators can be explained through the truth table. Table 2.3 gives various logical operations on operand a and b, and the corresponding results.

For example, suppose there is a declaration as follows:

then the value of logical expression (a>b)&&(x>y) is false.

5.Conditional Operator and Conditional Expressions

The only ternary operator in C++ is the conditional operator “?”, which can realize a simple selection. The form of the conditional expression is:

expression 1 must be a bool-type expression. expression 2 and 3 can be of any type, and the two types can be different. The result type of the conditional expression is the higher type of expression 2 and 3 (we will explain this when we introduce type conversion).

The execution order of the conditional expression is: first estimate expression 1. If expression 1 is true, then calculate expression 2, and the value of expression 2 is the final result; if expression 1 is false, then calculate expression 3, and the value of expression 3 is the final result. Note that the precedence of the conditional operator is higher than assignment operators but lower than that of logical operators. The associativity acts from right to left.

Now let us have a look at an example of conditional expressions:

a)Let a and b be two integer variables, then the expression (a<b)?a:b is to get the smaller integer between the two

b)Let the variable score store the score of one student; now we need to determine whether it is greater than or equal to 60. If so, then output “pass”, otherwise output “fail”. The following statement can achieve this function:

6.sizeof Operator

The sizeof operator is used to calculate the number of bytes a certain type of object occupies in memory. Its form of use is:

The result is the number of bytes occupied by the type specified by “type name”, or that occupied by the result type of “expression”. Note that this calculation process does not calculate the expression in the brackets.

7.Bitwise Operator

In the beginning of this chapter we mentioned that the C language has both the advantages of high-level languages and assembly languages. Bitwise operation embodies this advantage. Normally, the smallest data unit that high-level languages can deal with is bytes. But C is able to perform bitwise operations, and this advantage has now been fully inherited by C++. C++ provides 6 bitwise operators that can perform bitwise operations on integers.

a)Bitwise and(&)

The bitwise and operator applies the logical and operation on each corresponding bit of the two operands.

For example: compute 3 & 5

By performing the bitwise and operation we can set designated bits in an operand to 0 (the other bits of the operand remain the same); or read out designated bits in an operand. See the following two examples:

1.The following statement sets the lowest bit of a char-type variable a to 0:

2.Suppose there is char c; int a; The following statement reads out the lowest byte of a, and assigns it to c:

b)Bitwise or(|)

The bitwise or operation applies the logical or operation on each corresponding bit of the two operands.

For example: compute 3 | 5

By performing the bitwise or operation we can set designated bits of an operand to 1 (the other bits of the operand remain the same). For example: set the lowest 8 bits of an int-type variable a to 1:

c)Bitwise xor(^)

The bitwise xor operation applies the exclusive or operation on each corresponding bit of the two operands. The rule of operation is: if two bits on the same bit position of the two operands are same, then the bit on that position of the result is 0; otherwise, it is 1.

For example: compute 071^052

By performing the bitwise exclusive or operation, we can flip designated bits of an operand. The result of (bit ^ 0) is the original value of the bit. The result of (bit ^ 1) is the opposite of the original value.

For example: if we want to flip the lowest four bits of 01111010, we can do the xor operation on it with 00001111:

d)Bitwise complement(~)

Bitwise complement is a uniary operator, and it is used to flip each bit of a binary number. For example:

025:0000000000010101025:1111111111101010

Fig. 2.2: The process of a>>2.
Fig. 2.3: The process of 2<<1.
e)Shift

In C++ there are two shift operators: the left shift operator (<<) and right shift operator (>>). Both of them are binary operators. The left operand of a shift operator is the number you want to perform the shift on, and the right operand gives the number of bits you want to shift.

Left shift shifts the binary value of the operand leftwards according to the designated number of bits. After the left shift, the vacated low bits will be filled with zero while the high bits that have been shifted out will be discarded.

Right shift shifts the binary value of a number rightwards according to the designated number of bits. After the right shift, the operator will discard the low bits that have been shifted out. If the number is an unsigned number, the operator will fill the vacated high bits with zero; if the number is a signed number, then the operator will fill the vacated high bits with zero or the sign bit depending on different systems. In VC++6.0, it fills the vacated bits with the sign bit.

Look at two examples:

  1. If the value of a char-variable a is −8, then its complement code is 11111000. The value of expression a>>2 is −2. Figure 2.2 shows the process of this shift operation.
  2. The value of expression 2<<1 is 4. Figure 2.3 shows the process.

Note that the result of a shift operation is the value of the expression (a>>2 and 2<<1 in the above examples), while the value of the left operand of the shift operator (variable a and constant 2 in the above examples) will not change.

8.Operator Precedence

Table 2.4 lists the precedence and associativity of each operator in C++. Some of them have already been introduced, and others will be introduced in the following chapters.

9.Data type Conversions

We need type conversion when an operator in an expression has operands of different types. There are two kinds of type conversion: implicit conversion and explicit conversion.

Tab. 2.4: Operator Precedence.

Precedence Operator Associativity
1 [] () . −> postposition ++ postposition −− left → right
2 preposition ++ preposition −− sizeof & * +(positive sign) −(negative sign) ~ ! right → left
3 (cast) right → left
4 .* −>* left → right
5 * / % left → right
6 + − left → right
7 << >> left → right
8 < > <= >= left → right
9 == != left → right
10 & left → right
11 ^ left → right
12 | left → right
13 && left → right
14 || left → right
15 ? : right → left
16 = *= /= %= += −= <<= >>= &= ^= |= right →left
17 , left → right
a)Implicit conversion

Arithmetic operators, relational operators, logical operators, bitwise operators, and assignment operators are all binary operators, and the types of their two operands need to be the same. If the types of the operands involved in arithmetic operations or relational operations are not the same, the compiling system will convert them to a common type automatically (i.e., implicit conversion). The basic rule of conversion is to convert the lower data types into the higher data types. Here, a higher data type means greater data scope and higher precision. The order of basic data types (except for bool) is:

Table 2.5 shows the rules of implicit conversion. This kind of conversion is safe because there is no loss of accuracy during the conversion.

The type of operands involved in the logical operations must be bool. If operands are of other types, the compiling system will convert them into the bool type automatically. The method is: convert nonzero data to true and zero to false.

The operands of bitwise operations must be integers. If the operands of a bitwise operation are different types of integers, the compiling system will do implicit conversions according to the rules in Table 2.5.

Tab. 2.5: Data Type Conversion.

Condition Conversion
One long-double-type operand Convert the other operand to long double type.
Does not meet the condition above, and there is one double-type operand Convert the other operand to double type.
Does not meet the conditions above, and there is one float-type operand Convert the other operand to float type.
Does not meet the conditions One unsigned-long-type operand Convert the other operand to unsigned long type.
above (none of the two operands are float-type) One long-type operand, the other unsigned int type Convert the other operand to unsigned long type.
Does not meet the conditions above, and there is one long-type operand Convert the other operand to long type.
Does not meet the conditions above, and there is one unsigned-int-type operand Convert the other operand to unsigned int type.
Does not meet all the conditions above Convert both operands to int type.

In assignment operations, the type of lvalue (value on the left side of the assignment operator) must be the same as the type of rvalue (value on the right side of the assignment operator). If not so, the compiling system will do implicit conversions. Note that this kind of implicit conversion does not follow the rules in Table 2.5, but always converts the type of rvalue to the type of lvalue before the assignment.

The following program shows the rules of data conversion:

b)Explicit Conversion

Explicit conversion converts the result type of an expression to another designated type. Before the emergence of standard C++, there are two syntax forms of explicit conversion:

Explicit conversion converts the result type of the expression to the type designated by type name. For example:

Cast operators in standard C++ include: static_cast, dynamic_cast, const_cast, and reinterpret_cast. Their syntax forms are:

When using explicit conversion, note that:

Cast is not safe. From the examples above we can find out that, when converting a higher data type to a lower data type, there is a loss of precision.

Explicit conversion is temporary and one-time. For example, in the third row of the example above, cast operation int(Z) only takes out the value of float-type variable Z, converts it to int type temporarily and then assigns it to whole_part. At this time, the value of the memory unit that variable Z occupies does not really change. Therefore, when we use Z again, Z is still a float-type value.

2.2.6Statement

Statements control the execution flow of a program, and executing a statement will cause corresponding results. C++ statements include the declaration statement, expression statement, case statement, loop statement, jump statement, compound statement, and label statement. For example, the declaration of a variable is achieved by a declaration statement; adding a semicolon (;) at the end of an expression can make it an expression statement; enclosing several statements with a pair of brackets can constitute a compound statement. We will introduce other statements in the following chapters.

Note that there are no assignment statements and function call statements in C++, and we have to use expressions to achieve assignment and function call. We have already introduced assignment expressions in Chapter 2.2.5, and we will introduce function calls in Chapter 3.

Adding a semicolon at the end of an assignment expression will make it a statement. For example:

a=a+3;

It is an expression statement, and it achieves the same function as an assignment statement.

The difference between an expression and expression statement is: an expression can be a part of another compound expression and continue to participate in operations, while a statement does not have this function.

2.3Data Input and Output

2.3.1I/O Stream

In C++, the movement of data from one object to another is abstracted as a “stream”. One should establish a stream before using it, and delete it after use. To get data out from a stream is called an extract operation, and to put data into a stream is called an insert operation. I/O stream is used to achieve data input and output, and cin and cout are predefined stream-type objects. cin dealswith standard inputs, i.e., input from terminal. cout deals with standard outputs, i.e., output directed to terminal.

2.3.2Predefined Input and Output Operator

“<<” is the predefined input operator. Using it on the stream-type object cout can achieve most general screen outputs. The format is:

You can use successive output operators in one output statement to output several data items. You can write any compound expression after the output operator, and the compiling system will calculate its value and deliver it to the output operator automatically. For example:

It outputs the character string “Hello!” to the screen and then jumps to a new line.

It outputs the character string “a+b=” and the result of a+b successively to the screen.

The most general keyboard input is to use the input operator on stream-type object cin. The format is:

In an input statement, one can write several input operators contiguously, each followed by an expression that stores the input variable. For example:

To input two int-type numbers from the keyboard, we can use space to separate the two numbers. If one enters:

Then the value of variable a is 5 and the value of variable b is 6.

2.3.3Simple I/O Format Control

When using cin and cout for data input and output, computers can process any type of data according to the default format automatically. But this is not enough. We often need special formats. There are many ways to set a format, and we will detail them in Chapter 11. In this section we only introduce the simplest format control.

A C++ I/O-stream library provides some operators that can be directly embedded into the input/ output statements to achieve I/O format control. To use these operators, we should first include an iomanip head file at the beginning of the source program. The commonly used I/O-stream library operators are listed in Table 2.6.

For example, if you want to output a floating number 3.1415 to the screen and jump to a new line, you can set the field width to five characters and keep two significant digits after the decimal point. The output statement would be:

Tab. 2.6: Commonly Used I/O-stream Library Operators.

Operator Name Meaning
Dec Use decimal system to represent data
Hex Use hexadecimal system to represent data
Oct Use octal system to represent data
Ws Extract blank characters
Endl Insert line break and flush the stream
Ends Insert the null character
setprecision (int) Set decimal digits of a floating number (include decimal point)
setw (int) Set field width

2.4The Fundamental Control Structures of Algorithms

After studying data types, expressions, assignment statements, and data input/ output, we can write programs that can achieve simple functions. However, the programs we can write now are only statement sequences of an ordered execution. In fact, the objective world is not that simple, and the ways to solve problems usually cannot be described clearly using this kind of ordered steps.

For example: the following piecewise function calculates the value of y when entering a value of x.

y={101(x<0)(x=0)(x>0)

It is not hard to calculate this problem manually, while the question is how to use programming languages to describe this calculation clearly and instruct the computer to do the calculation. Apparently, we cannot describe it using an ordered statement sequence. We must pass judgment be selective here: we need to use selective control structures.

See another simple example: count the average height of an arbitrary crowd. This is a simple calculation that even primary school students can do. But when the statistical data amount is very large, we have to use computers. The only advantage of a computer is its high calculation speed, since we have to describe the calculation method accurately for it. The major part of this algorithm is the accumulation, although to repeat the same action many times using ordered statements is clearly inappropriate (and impossible when there are large amounts of data). In this case we need a loop control structure.

There are three types of basic control structures: the sequential structure, case structure, and loop structure. The simplest one is the sequential structure, which we have already studied. Here we will introduce the case structure and loop structure. First of all, we will introduce program flow charts. A flow chart is used to describe an algorithm. Compared with natural language, a flow chart is simple, intuitive, and accurate. The symbols used in flow charts are listed in Figure 2.4.

Fig. 2.4: Standard symbols in flow charts.
Fig. 2.5: Flow chart of statement if else.

2.4.1Achieving Case Structure Using if Statement

if statements are designed to achieve case structure. Their syntax form is:

The execution order is: firstly evaluate the expression; if the expression is true, execute statement 1; otherwise execute statement 2. The flow chart of an if statement is shown in Figure 2.5.

Here Statement 1 and 2 can also be several statements enclosed in brackets (known as a compound statement).

For example:

The above statements output the larger number between x and y.

Statement 2 can be empty. When statement 2 is empty, we can ignore else, and the syntax form becomes as the following:

For example:

Example 2.2: Input a certain year and determine whether it is a leap year.

Analysis: a leap year is divisible by 4 but indivisible by 100, or is divisible by 400. Therefore, we can first store the value of the input year into the variable year, and then evaluate the expression ((year%4 == 0 && year%100 != 0) || (year%400 == 0)). If the expression is true, then the input year is a leap year; otherwise it is not.

Source code:

The result (the underlined part is the input content, the rest is output content. All the examples afterwards are the same) is:

2.4.2Multiple Selection Structure

There are many problems that cannot be solved by only one simple selection, and they need multiple judgments and selections. There are several methods to achieve multiple selection structures:

1.Nested if Statement

Syntax form:

Attention: statement 1, 2, 3, and 4 can be a compound statement; the if of each hierarchy has to match with an else. If you want to omit one else, you must use {} to enclose the if statement of that hierarchy to force the correct hierarchy relation.

Example 2.3: Compare two numbers.

Analysis: compare two numbers x and y; there are three resulting possibilities: x=y, x>y, and x<y. Therefore, we need a multiple selection structure. We choose the nested if else statement here.

Source code:

Result 1:

Result 2:

Result 3:

2.if... else if Statement

If all the nested if statements are in a branch else,we can use the statement if...else if. The syntax form is:

Fig. 2.6: Flow chart of statement if...else if.

Statement 1, 2, 3, ... n can be a compound statement. The execution order of the statement if...else if is shown in Figure 2.6.

3.switch Statement

In some problems, though there need to be multiple selections, each judgment evaluates the same expression, and thus it is not necessary to calculate the value of the expression in each nested if statement. The switch statement is designed to solve this problem in C++. The syntax form is:

The execution order of a switch statement is: first calculate the value of the expression in a switch statement; then find the first case labeled by a constant expression that matches the value of the expression, use the case as an entry label, and start execution. If no case matches the value of the expression, then execute from “default:”.

You should pay attention to the following issues when using switch statements:

The expression in switch statements can be int-type, character-type, or enumeration-type.

Thevalueofeachconstant expression must be different, although their sequence order does not affect the execution result.

There can be several statements in each case, and you do not need to use {}.

Each case is only an entry label, and it cannot decide the endpoint of the execution. So you need to add a break statement at the end of a case branch to exit early from the whole switch structure; otherwise execution will fall through to the next statement when the code of that case branch is done.

When several branches need to do the same action, they can use the same group of statements.

Example 2.4: Enter an integer between 0~6, convert it into the corresponding day of week, and then output it.

Analysis: In this example, the number entered decides the output information, because numbers 0~6 represent seven conditions: “Sunday”, “Monday”.... Thus we need to use a multiple selection structure. Since it is judging the day of the week, a switch statement is most appropriate.

Source code:

Running sample:

2.4.3Loop Structure

There are three kinds of loop control structures in C++:

1.while statement

Syntax form:

Execution order: first evaluate the expression (loop condition); if it is true, execute the loop body (statement) and re-evaluate the expression; continue the cycle until expression becomes false. When using while statement, generally there should be statements in the loop body that can change the value of expression, i.e., the loop condition, otherwise it will be an infinite loop (dead loop).

Figure 2.7 is the flow chart of a while statement.

When using while statement, generally there should be statements in the loop body that can change the value of expression, i.e., the loop condition, otherwise it will be an infinite loop (dead loop).

Example 2.5: Calculate the sum of numbers 1~10.

Analysis: we need to use an accumulation algorithm here. An accumulation process is a loop process, and it can be achieved by a while statement.

Source code:

Fig. 2.7: Flow chart of statement while.

Result:

2.do-while Statement

Syntax form:

The execution order is: execute loop body statement first, and then evaluate the expression (loop condition). If the expression is true, continue the execution-evaluation cycle; otherwise end the loop. Figure 2.8 is the flow chart of a do-while statement.

Like in while statements, generally there should be statements in the loop body that can change the value of expression; otherwise it will be a dead loop.

Example 2.6: Enter an integer and output in the reverse order of each digit of the integer.

Analysis: output each digit of an integer the reversed order is to first output the ones of the integer, and then its tens, its hundreds.... We can divide the integer by 10 continuously until the quotient is 0. This is a loop process, and no matter which integer it is, we have to output at least one digit (even if it is 0). Therefore, we can use a do-while loop statement: first execute the loop body and then evaluate the loop condition.

Fig. 2.8: Flow chart of do-while statement.

Source code:

Result:

Both the do-while statement and while statement achieve the loop structure, while the difference between the two is: the while statement first evaluates the expression, and executes the loop body only if the expression is true; the do-while statement first executes the loop body and then evaluates the expression, and the loop body is always executed at least once. Example 2.7 achieves the same function as Example 2.5, using a do-while statement.

Example 2.7: Use a do-while statement to calculate the sum of numbers 1~10.

Result:

We can see that the result is the same as in Example 2.5. Most of the time, if the loop conditions and the loop bodies of the while loop and the do-while loop are both the same, the results of the two loops are the same. This is because inmost cases, the loop condition at the beginning of the loop is true, so whether or not one first considers the loop condition does not affect the result. But if the loop condition at the beginning of the loop is false, the do-while loop will at least execute loop body once, while the while loop will not execute the loop body at all. Now we make a little change in Example 2.5 and 2.7: integer i now is to be input from the keyboard. Please analyze the results of the two programs below in both conditions, where variable i is greater than 10 and not.

Program 1:

Program 2:

3.for Statement

The use of for statements is the most flexible. They can be used when the number of loops is either certain or not. The syntax form of a for statement is as below:

Figure 2.9 is the flow chart of a for statement.

We can see from Figure 2.9 that the execution flow of a for statement is: first calculate the value of expression 1, and then evaluate expression 2 (loop condition). If expression 2 is true, execute the statements in the loop body once; otherwise quit the loop. After each execution of the loop body, calculate expression 3 and then re-evaluate expression 2 to decide whether to continue the execution or not.

Some important points about for statements:

Expression 1, 2, and 3 can be omitted, but you cannot omit the semicolons between them. If you omit the three expressions, the statement form becomes:

This will become a dead cycle.

Fig. 2.9: Execution flow of a for statement.

Expression 2 is the loop condition, so omitting it will cause a dead cycle.

Expression 1 is often used to initialize the loop condition. It can also be an expression that is independent of the loop variable. If you omit expression 1 or if it is independent of the loop condition, you must initialize the loop condition before the for statement. See the following three program segments:

Program segment 1:

Program segment 2:

Program segment 3:

Expression 1 and expression 3 can be simple expressions or comma expressions. For example:

Expression 3 is often used to change the loop condition. If expression 3 is omitted or independent of the loop condition, there should be other statements in the loop body that can change the loop condition to make sure that the cycle ends normally, such as:

If there only exists expression 2, and expression 1 and 3 are omitted, the for statement becomes the same as the while statement. For example, the program segments below are the same:

A for statement is a highly functional loop statement, including all the functions of while statements. Besides giving the loop condition, it also can do initialization, increase the loop variable automatically, and so on. for statements can solve all loop problems in programming.

Example 2.8: Enter an integer and calculate all its factors.

Analysis: we can use the enumeration method to get all the factors of integer n: consider integers 1~n, any number that can dividen exactly is a factor of n. It is a loop with known cycle times, so we can use a for statement. Source code:

Result 1:

Result 2:

2.4.4Nestings of Loop Structure and Case Structure

1.Nested Case Structure

As already stated, we can achieve multiple selections using nested case structures.

2.Nested Loop Structure

We can construct a multiple loop structure by including one loop structure in the loop body of another loop structure. The three kinds of loop statements, while, do-while, and for, can nest each other. For example, in the following program a do-while loop is nested in a for loop:

Example 2.9: Write a program that can output the following pattern:

Source code:

3.Mutual Nesting between Loop Structure and Case Structure

Loop structure and case structure can also nest each other to implement complex algorithms. Any branch of a case structure can nest a whole loop structure, and the loop body of a loop structure can nest a whole case structure. For example, the following program is for finding the numbers between 100 and 200 that cannot be divided exactly by 3. In the example, an if statement is nested in the loop body of a for statement:

Example 2.10: Read a series of integers, and count the number of positive integers (stored in variable i) and the number of negative integers (stored in variable j). If the input integer is 0 then end the program.

Analysis: we need to read a series of integers, while the number of integers is uncertain. We have to make a decision after each reading of a number: if the number input is not 0, we process the number and continue reading; otherwise we finish the work. Therefore, the while-loop is the most appropriate structure to use, and the loop control condition should be n!=0. Because we have to count the number of positive integers and negative integers respectively, we need to nest a case structure inside the loop body.

Source code:

Result:

2.4.5Other Control Statements

1.break Statement

break statements are used inside switch statements or a loop body to provide an immediate exit from the switch statement or the loop body. Execution will then continue from the next statement of the switch statement or the loop structure. break statements should not be used elsewhere.

2.continue Statement

continue statements can be used inside a loop body to end this loop, and then start the next loop if the loop condition is satisfied.

3.goto Statement

The syntax form of a goto statement is:

Statement labels are used to label a statement. They are placed at the front of the statement, and are separated from the statement by a colon (:).

goto statements are used to make the execution flow jump to the statement specified by the statement label. The use of a goto statement will destroy the structure of a program, and we should avoid using it.

2.5User-Defined Data Type

C++ not only has abundant built-in basic data types, but also allows users to define data types themselves. User-defined data types include: the enumeration type, structure type, union type, array type, class type, and so on. Wewill introduce the enumeration type, structure type, and union type in this section, and the rest will be introduced in the following chapters.

2.5.1typedef Declaration

When writing a program, besides built-in data type names and user-defined data type names, we can also create new names for a known data type. In this way, we can give a known type a specific name based on different applications, thus to improve the readability of the program. Also, creating a shorter name for an existed long type name can make the program more concise. typedef is used to declare an identifier as another name of a data type, and the identifier can then be used as the data type name.

The syntax form of typedef declaration is:

There can be several identifiers in the name list of new type names, which are separated by commas. In this way, we can give several names to a known data type in one typedef statement.

For example:

2.5.2Enumeration Type – enum

Readers must have experienced this kind of situation when solving problems: win, lose, tie, and cancel are the only four results of a game; there are only red, yellow, blue, white, and black balls in a bag; there are only seven days in one week, etc. The data variables above all have limited possible values. Though we can use int-type or char-type to represent them, validity checks on data values would become troublesome. For example, if we use integers from 0 to 6 to represent the seven days in one week, then if the variable value is 8, it is invalid. Enumeration type in C++ is designed to solve this problem.

We can construct an enumeration type by listing all the possible values of a variable. The declaration form of an enumeration type is:

For example:

Notes on using an enumeration type:

Enumeration elements should be treated as constants, and they cannot be assigned. For example, the following statement is illegal:

Enumeration elements have default values which are: 0, 1, 2, .... For example, the value of sun in the example above is 0, and mon is 1, tue is 2, ..., sat is 6.

One can also specify the value of enumeration elements, such as:

The statement defines sun as 7 and mon as 1. The following unspecified elements will in turn have values greater by 1 than their previous, thus tue will be 2, ..., sat will be 6.

Enumeration values can be used in relational calculations directly.

Integer values cannot be assigned to enumeration variables directly. If the assignment is needed, we should perform a cast first.

Example 2.11: There are four possible results in one game: win, lose, tie, and cancel. Write a program to output these four situations.

Analysis: because there are only four possible results in a game, we can declare an enumeration variable and use it to store the results of the game.

Source code:

Result:

Notice:

The above two statements are both right. After declaring an enumeration type, we do not need to write the keyword enum before the type name when declaring a variable.

2.5.3Structure

We have learned basic data types and the enumeration type (a collection of integers) so far, while in many cases we need to combine different data types together. For example, consider the student number, name, age, and score of one student. Although they are of different data types, they are closely related in that they belong to one person. In this case, we need to declare a structure type for this group of information. Structure type is a collection of different types of data, and its declaration form is as below:

For example:

It declares a structure of student information.

To use structure-type data, only declaring the structure type is not enough, since we also have to declare the structure variables. The syntax form of structure variable declaration is:

Notice:

Structure variable declaration is after the structure type declaration, while they can also be done at the same time.

Youcanusethesizeof operation to calculate how many bytes the structure variable occupies in memory.

You can initiate a structure variable while declaring it.

The form of referencing a member of a structure is:

Example 2.12: The initialization and use of a structure variable.

Result:

The same type of data can also construct a structure. The structure animal in Example 2.13 is made up of two int-type members.

Example 2.13: There are three animals and all of them have two attributes: weight and height. Now we need to assign their weights and heights, and then output their weights.

Analysis: these three animals all have a weight and height attribute; therefore we can declare a structure that includes the two attribute members (weight and height).

Source code:

Result:

2.5.4Union

Sometimes several different types of data need to share the same storage area. In this case we can declare a union type. The syntax form of a union type declaration is:

Syntax form of union-type variable declaration:

Syntax form of referencing a member of a union-type variable:

Fig. 2.10: Storage structure of a variable of union type uarea.

For example, the following is a declaration of a union type:

Figure 2.10 is the storage structure of a variable of union type uarea.

A union type may have no name when it is declared, and at this time it is called an unnamed union. Unnamed unions do not have names; they only declare a collection of members that have the same memory address. We can access these members by their member names directly.

For example, declare an unnamed union:

We can use it in a program like this:

i=10:f=2.2;

An unnamed union is usually used as a nested member in a structure body, see Example 2.14.

Example 2.14: A structure that can describe fighters, bombers, or transport planes.

Result:

2.6Summary

C++ is evolved from C. Dennis Ritchie from Bell Labs created the C language on the basis of the B language in 1972. It has many advantages: concision and flexibility, plenty of operators and data structures, structured control statements, high execution efficiency of procedures, and having both the advantages of a high-level language and an assembly language.

C++, a general-purpose programming language, was created by Dr. Bjame Stroustrup from AT&T Bell labs in 1980. C++ was developed to support the object-oriented program designs based on the C language. C++ has two main features: one is that it is fully compatible with C; the other is that it supports object-oriented methods.

Data is the processing object in programs, which can be classified by its characteristics. Data types in C++ can be divided into basic types and user-defined types. Basic types are predefined in the C++ compiling system, including the bool type, char (character) type, int (integral) type, float type (represent real numbers), and double type (double precision floating point type, or double precision type). Apart from the bool type, these basic types can be classified into two categories: integer type and float type. Here char type is an integer type essentially: it is an integer whose length is 1 byte, and is usually used to store the ASCII code of characters. C++ language does not only have abundant predefined basic types, but also allows user-defined types. User-defined types include enumeration type, structure type, union type, array type, class type, and so on. We introduced enumeration type, structure type, and union type in this chapter. Class type is the core of C++ object-oriented program design, and it is the main content of the following chapters. The other user-defined data types will also be introduced in the following chapters. We introduced the basic methods of data input/ output in this chapter.

Program design includes data structure design and algorithm design. An algorithm is made up of a sequence of control structures. Sequential, case, and loop structures are the basic control structures in program design and they are the basis of constructing complex algorithms.

Exercises

2.1 What are the main characteristics and advantages of C++?

2.2 Which of the following identifiers are legal?

2.3 What is the effect of each statement in Example 2.1?

2.4 What is the advantage of using the keyword const instead of using a #define statement?

2.5 Please write a statement in C++ that declares a constant PI with the value of 3.1415; and then declare a float variable a, and assign the value of PI to a.

2.6 What is the value of BLUE in the following enumeration type?

2.7 What is the use of comments? Which comment forms does C++ have? What are their differences?

2.8 What is an expression? Is x=5+7 an expression? What is its value?

2.9 What are the values of the following expressions?

a) 201 / 4
b) 201 % 4
c) 201 / 4.0

2.10 What is the value of variables a, b, and c after executing the following statements?

a=30;b=a++;c=++a;

2.11 Can we initialize several variables in a for statement? How to achieve this?

2.12 What is the value of n after executing the following statements?

intn;for(n=0;n<100;n++);

2.13 Write a for statement: the loop condition is that n is between 100 and 200, and step length is 2; then use a while and do...while statement to do the same loop.

2.14 What is the difference between statements if ( x = 3 ) and if (x = = 3)?

2.15 What is a scope? What is a local variable? What is a global variable? How does one use a global variable?

2.16 Given two variables x and y, write a simple if statement to assign the smaller value of the two variables to the variable that has the greater value.

2.17 Correct the errors in the following program. What is the result after your correction?

2.18 Write a program to prompt users to enter a number and then show the number on the screen.

2.19 Which data types does C++ have? List the range of each data type. Write a program to show the number of bytes every data type occupies in the computer you are using.

2.20 Write a program to output the ASCII code of characters that are between 32 and 127.

2.21 Run the following program and observe the output. Is it the same as you think?

2.22 Run the following program, observe the output, and figure the difference between i++ and ++i.

2.23 What is a constant? What is a variable?

2.24 Which storage types do variables have?

2.25 Write down the values of the following expressions:

a) 2 < 3 &&6 < 9
b) ! ( 4<7 )
c) ! ( 3 > 5) || (6 < 2 )

2.26 If a = 1, b = 2, c = 3, then what are the results of the following expressions?

a) a | b − c
b) a ^ b & − c
c) a & b | c
d) a | b & c

2.27 If a = 1, then what are the results of the following expressions?

a) ! a | a
b) ~ a | a
c) a ^ a
d) a >> 2

2.28 Write a program to achieve this function: ask the user “Is it raining now?” and prompt the user to enter Y or N. If the user enters Y, then display “It is raining now.”; if N is entered, then display “It is not raining now.”; otherwise, continue asking “Is it raining now?”

2.29 Write a program that asks the user “What score did you get? (0~100).” Once an input is received, judge and output its rank. The rules are as below:

Rank={ABCD90score10080score<9060score<800score<60

2.30 Implement a simple menu program: when executing, display “Menu: A(dd) D(elete) S(ort) Q(uit), Select one:” to prompt users to enter a letter. Here A represents add, D represents delete, S represents sort, and Q represents quit. When the user enters A, D, or S, display “Data has been added/ deleted/sorted.” correspondingly; when the input is Q, end the program.

  1. Use an if...else statement to judge the inputs and use break and continue to control the flow.
  2. Use a switch statement.

2.31 Use the enumeration method to find out all the prime numbers between 1 and 100 and display them. Use a while, do-while, and for loop statement respectively.

2.32 Compare the different usages between a break statement and continue statement.

2.33 Declare a structure type that represents time. It can show year, month, day, hours, minutes, and seconds. Prompt the user to enter the value of year, month, day, hours, minutes, seconds, and then display them.

2.34 Define an integer variable in a program and assign it a value between 1 and 100. Prompt the user to guess the value, compare the two values, and show the comparing result to the user. Continue the guess until the user gives the right answer. Use a while and do-while loop statement respectively.

2.35 Declare an enumeration type weekday that includes seven elements (from Sunday to Saturday). Declare a variable of the weekday type and assign it a value. Then declare an int-type variable. See if you can assign the int-type variable the value of the weekday-type variable.

2.36 There are several balls of colors red, yellow, blue, white, and black in the pocket. Picking three balls of different colors each time, how many possibilities are there?

2.37 Output the multiplication table.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset