Заглавная страница Избранные статьи Случайная статья Познавательные статьи Новые добавления Обратная связь FAQ Написать работу КАТЕГОРИИ: АрхеологияБиология Генетика География Информатика История Логика Маркетинг Математика Менеджмент Механика Педагогика Религия Социология Технологии Физика Философия Финансы Химия Экология ТОП 10 на сайте Приготовление дезинфицирующих растворов различной концентрацииТехника нижней прямой подачи мяча. Франко-прусская война (причины и последствия) Организация работы процедурного кабинета Смысловое и механическое запоминание, их место и роль в усвоении знаний Коммуникативные барьеры и пути их преодоления Обработка изделий медицинского назначения многократного применения Образцы текста публицистического стиля Четыре типа изменения баланса Задачи с ответами для Всероссийской олимпиады по праву Мы поможем в написании ваших работ! ЗНАЕТЕ ЛИ ВЫ?
Влияние общества на человека
Приготовление дезинфицирующих растворов различной концентрации Практические работы по географии для 6 класса Организация работы процедурного кабинета Изменения в неживой природе осенью Уборка процедурного кабинета Сольфеджио. Все правила по сольфеджио Балочные системы. Определение реакций опор и моментов защемления |
Ternopil national economic university (TNEU)Содержание книги Поиск на нашем сайте
FACULTY OF COMPUTER INFORMATION TECHNOLOGIES AMERICAN-UKRAINIAN SCHOOL OF COMPUTER SCIENCE
LAB MANUAL of discipline “Algorithmization and Programming” for students of specialty 6.050101 – “Computer Science”
Ternopil Lab manual of discipline “Algorithmization and Programming” / I.Paliy, M.Komar. – Ternopil. – 2012. – 68 p. Approved by Department of Information Computing Systems and Control Meeting, Protocol # 11 of 15 May 2012
Author: Ihor Paliy, PhD, Assistance Professor of the Department for Information Computing Systems and Control, TNEU Myroslav Komar, Lecturer of the Department for Information Computing Systems and Control, TNEU
Reviewers: Anatoly Sachenko, DSc, Professor, Head of the Department for Information Computing Systems and Control, TNEU
Vasyl Yatskiv, PhD, Associate Professor, Department of Specialized Computer Systems, TNEU
CONTENT
INTRODUCTION Since its introduction less than a decade ago, C++ has experienced growing acceptance as a practical object-oriented programming language suitable for teaching, research, and commercial software development. The language has also rapidly evolved during this period and acquired a number of new features (e.g., templates and exception handling) which have added to its richness. It is the basis for Java, JavaScript and C#. This course is designed to present the basics of the language in a straight forward, easy to understand manner. It studies students the approaches for solving different problems using algorithms development and following computer programming. It teaches how to program in C++ and how to properly use its features. It does not attempt to teach object-oriented design to any depth. At the completion of this course, the student will be able to 1. Design algorithmic solutions to problems; 2. Understand the structure of a C/C++ language program including the use of variable definitions, data types, functions, scope and operators; 3. Translate a specific algorithm into correct, good commented C++ code using generally accepted programming style using: - various forms of Input/Output including files; - assignments; - if-else logic; - while, do, and for loops; - functions; - arrays; - strings and string functions, etc. 4. Be able to test a program, find and correct compile-time, run-time and logic errors.
Lab #1. C++ OPERATORS Goal: Learn how to program solutions for simple computing problems using C++ operators. Theory Arithmetic Operators C++ provides operators for composing arithmetic, relational, logical, bitwise, and conditional expressions. It also provides operators which produce useful side-effects, such as assignment, increment, and decrement. We will look at each category of operators in turn. We will also discuss the precedence rules which govern the order of operator evaluation in a multi-operator expression. C++ provides five basic arithmetic operators. These are summarized in the Table below.
Except for remainder (%) all other arithmetic operators can accept a mix of integer and real operands. Generally, if both operands are integers then the result will be an integer. However, if one or both of the operands are reals then the result will be a real (or double to be exact). When both operands of the division operator (/) are integers then the division is performed as an integer division and not the normal division we are used to. Integer division always results in an integer outcome (i.e., the result is always rounded down). For example:
9 / 2 // gives 4, not 4.5! -9 / 2 // gives -5, not -4!
Unintended integer divisions are a common source of programming errors. To obtain a real division when both operands are integers, you should cast one of the operands to be real:
int cost = 100; int volume = 80; double unitPrice = cost / (double) volume; // gives 1.25
The remainder operator (%) expects integers for both of its operands. It returns the remainder of integer-dividing the operands. For example 13%3 is calculated by integer dividing 13 by 3 to give an outcome of 4 and a remainder of 1; the result is therefore 1. It is possible for the outcome of an arithmetic operation to be too large for storing in a designated variable. This situation is called an overflow. The outcome of an overflow is machine-dependent and therefore undefined. For example:
unsigned char k = 10 * 92; // overflow: 920 > 255
It is illegal to divide a number by zero. This results in a run-time division-by-zero failure which typically causes the program to terminate.
Relational Operators C++ provides six relational operators for comparing numeric quantities. These are summarized in the Table below. Relational operators evaluate to 1 (representing the true outcome) or 0 (representing the false outcome).
Note that the <= and >= operators are only supported in the form shown. In particular, =< and => are both invalid and do not mean anything. The operands of a relational operator must evaluate to a number. Characters are valid operands since they are represented by numeric values. For example (assuming ASCII coding):
'A' < 'F' // gives 1 (is like 65 < 70)
The relational operators should not be used for comparing strings, because this will result in the string addresses being compared, not the string contents. For example, the expression
"HELLO" < "BYE"
causes the address of "HELLO" to be compared to the address of "BYE". As these addresses are determined by the compiler (in a machine-dependent manner), the outcome may be 0 or may be 1, and is therefore undefined. C++ provides library functions (e.g., strcmp) for the lexicographic comparison of string. These will be described later in the book.
Logical Operators C++ provides three logical operators for combining logical expression. These are summarized in the Table below. Like the relational operators, logical operators evaluate to 1 or 0.
Logical negation is a unary operator, which negates the logical value of its single operand. If its operand is nonzero it produces 0, and if it is 0 it produces 1. Logical and produces 0 if one or both of its operands evaluate to 0. Otherwise, it produces 1. Logical or produces 0 if both of its operands evaluate to 0. Otherwise, it produces 1. Note that here we talk of zero and nonzero operands (not zero and 1). In general, any nonzero value can be used to represent the logical true, whereas only zero represents the logical false. The following are, therefore, all valid logical expressions:
!20 // gives 0 10 && 5 // gives 1 10 || 5.5 // gives 1 10 && 0 // gives 0
Increment/Decrement Operators The auto increment (++) and auto decrement (--) operators provide a convenient way of, respectively, adding and subtracting 1 from a numeric variable. These are summarized in the Table below. The examples assume the following variable definition:
int k = 5;
Both operators can be used in prefix and postfix form. The difference is significant. When used in prefix form, the operator is first applied and the outcome is then used in the expression. When used in the postfix form, the expression is evaluated first and then the operator applied. Both operators may be applied to integer as well as real variables, although in practice real variables are rarely useful in this form.
Assignment Operator The assignment operator is used for storing a value at some memory location (typically denoted by a variable). Its left operand should be an lvalue, and its right operand may be an arbitrary expression. The latter is evaluated and the outcome is stored in the location denoted by the lvalue. An lvalue (standing for left value) is anything that denotes a memory location in which a value may be stored. The only kind of lvalue we have seen so far in this book is a variable. The assignment operator has a number of variants, obtained by combining it with the arithmetic and bitwise operators. These are summarized in the Table below. The examples assume that n is an integer variable.
An assignment operation is itself an expression whose value is the value stored in its left operand. An assignment operation can therefore be used as the right operand of another assignment operation. Any number of assignments can be concatenated in this fashion to form one expression. For example:
int m, n, p; m = n = p = 100; // means: n = (m = (p = 100)); m = (n = p = 100) + 2; // means: m = (n = (p = 100)) + 2;
This is equally applicable to other forms of assignment. For example:
m = 100; m += n = p = 10; // means: m = m + (n = p = 10);
Conditional Operator The conditional operator takes three operands. It has the general form:
operand1? operand2: operand3
First operand1 is evaluated, which is treated as a logical condition. If the result is nonzero then operand2 is evaluated and its value is the final result. Otherwise, operand3 is evaluated and its value is the final result. For example:
int m = 1, n = 2; int min = (m < n? m: n); // min receives 1
Note that of the second and the third operands of the conditional operator only one is evaluated. This may be significant when one or both contain side-effects (i.e., their evaluation causes a change to the value of a variable). For example, in
int min = (m < n? m++: n++);
m is incremented because m++ is evaluated but n is not incremented because n++ is not evaluated. Because a conditional operation is itself an expression, it may be used as an operand of another conditional operation, that is, conditional expressions may be nested. For example:
int m = 1, n = 2, p =3; int min = (m < n? (m < p? m: p): (n < p? n: p));
Comma Operator Multiple expressions can be combined into one expression using the comma operator. The comma operator takes two operands. It first evaluates the left operand and then the right operand, and returns the value of the latter as the final outcome. For example:
int m, n, min; int mCount = 0, nCount = 0; //... min = (m < n? mCount++, m: nCount++, n);
Here when m is less than n, mCount++ is evaluated and the value of m is stored in min. Otherwise, nCount++ is evaluated and the value of n is stored in min.
The sizeof Operator C++ provides a useful operator, sizeof, for calculating the size of any data item or type. It takes a single operand which may be a type name (e.g., int) or an expression (e.g., 100) and returns the size of the specified entity in bytes. The outcome is totally machine-dependent. Listing below illustrates the use of sizeof on the built-in types we have encountered so far.
void main () { cout << "char size = " << sizeof(char) << " bytes\n"; cout << "char* size = " << sizeof(char*) << " bytes\n"; cout << "short size = " << sizeof(short) << " bytes\n"; cout << "int size = " << sizeof(int) << " bytes\n"; cout << "long size = " << sizeof(long) << " bytes\n"; cout << "float size = " << sizeof(float) << " bytes\n"; cout << "double size = " << sizeof(double) << " bytes\n"; cout << "1.55 size = " << sizeof(1.55) << " bytes\n"; cout << "1.55L size = " << sizeof(1.55L) << " bytes\n"; cout << "HELLO size = " << sizeof("HELLO") << " bytes\n"; }
When run, the program will produce the following output: char size = 1 bytes char* size = 2 bytes short size = 2 bytes int size = 2 bytes long size = 4 bytes float size = 4 bytes double size = 8 bytes 1.55 size = 8 bytes 1.55L size = 10 bytes HELLO size = 6 bytes
Operator Precedence The order in which operators are evaluated in an expression is significant and is determined by precedence rules. These rules divide the C++ operators into a number of precedence levels (see the Table below). Operators in higher levels take precedence over operators in lower levels. For example, in
a == b + c * d
c * d is evaluated first because * has a higher precedence than + and ==. The result is then added to b because + has a higher precedence than ==, and then == is evaluated. Precedence rules can be overridden using brackets. For example, rewriting the above expression as
a == (b + c) * d
causes + to be evaluated before *.
Operators with the same precedence level are evaluated in the order specified by the last column of the Table above. For example, in
a = b += c
the evaluation order is right to left, so first b += c is evaluated, followed by
Simple Type Conversion A value in any of the built-in types we have seen so far can be converted (type-cast) to any of the other types. For example:
(int) 3.14 // converts 3.14 to an int to give 3 (long) 3.14 // converts 3.14 to a long to give 3L (double) 2 // converts 2 to a double to give 2.0 (char) 122 // converts 122 to a char whose code is 122 (unsigned short) 3.14 // gives 3 as an unsigned short
As shown by these examples, the built-in type identifiers can be used as type operators. Type operators are unary (i.e., take one operand) and appear inside brackets to the left of their operand. This is called explicit type conversion. When the type name is just one word, an alternate notation may be used in which the brackets appear around the operand:
int(3.14) // same as: (int) 3.14
In some cases, C++ also performs implicit type conversion. This happens when values of different types are mixed in an expression. For example:
double d = 1; // d receives 1.0 int i = 10.5; // i receives 10 i = i + d; // means: i = int(double(i) + d)
In the last example, i + d involves mismatching types, so i is first converted to double (promoted) and then added to d. The result is a double which does not match the type of i on the left side of the assignment, so it is converted to int (demoted) before being assigned to i. The above rules represent some simple but common cases for type conversion. More complex cases will be examined later in the book after we have discussed other data types and classes.
Lab Overview 2.1. Read the theory and try Control Exercises. 2.2. Develop the algorithm flowchart to solve a problem according to individual case from the Table below. 2.3. Write the program code according to the developed algorithm. 2.4. Debug the program, run it and make screenshots. 2.5. Prepare the Lab Report according to the required structure.
Report Structure - Title page (Annex A) - Task overview - Algorithm’s flowchart - Program code - Program running screenshots - Conclusions
Control Exercises 4.1. Write expressions for the following: - To test if a number n is even. - To test if a character c is a digit. - To test if a character c is a letter. - To do the test: n is odd and positive or n is even and negative. - To give the absolute value of a number n. - To give the number of characters in a null-terminated string literal s.
4.2. Add extra brackets to the following expressions to explicitly show the order in which the operators are evaluated: (n <= p + q && n >= p - q || n == 0) (++n * q-- / ++p - q) (n | p & q ^ p << 2 + q) (p < q? n < p? q * n - 2: q / n + 1: q - n)
4.3. What will be the value of each of the following variables after its initialization? double d = 2 * int(3.14); long k = 3.14 - 3; char c = 'a' + 2; char c = 'p' + 'A' - 'a';
References 5.1. Juan Soulié. C++ Language Tutorial. – 2007. – p. 21-33. 5.2. Sharam Hekmat. C++ Essentials. – PragSoft Corporation 2005. – p. 17-29. 5.3. Prata S. C++ Primer Plus (5th Edition). – Sams, 2004. – p. 95-108. Lab #2. CONTROL STRUCTURES Goal: program the problem solving using C++ control structures Theory Statements represent the lowest-level building blocks of a program. A running program spends all of its time executing statements. The order in which statements are executed is called control flow. This term reflect the fact that the currently executing statement has the control of the CPU, which when completed will be handed over (flow) to another statement. Flow control in a program is typically sequential, from one statement to the next, but may be diverted to other paths by branch statements. Flow control is an important consideration because it determines what is executed during a run and what is not, therefore affecting the overall outcome of the program. Like many other procedural languages, C++ provides different forms of statements for different purposes. Declaration statements are used for defining variables. Assignment-like statements are used for simple, algebraic computations. Branching statements are used for specifying alternate paths of execution, depending on the outcome of a logical condition. Loop statements are used for specifying computations which need to be repeated until a certain logical condition is satisfied. Flow control statements are used to divert the execution path to another part of the program.
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Последнее изменение этой страницы: 2016-04-18; просмотров: 223; Нарушение авторского права страницы; Мы поможем в написании вашей работы! infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 18.225.117.89 (0.011 с.) |