1 / 136

CHAPTER 2 BASIC ELEMENTS OF C++

CHAPTER 2 BASIC ELEMENTS OF C++. In this chapter, you will: Become familiar with the basic components of a C++ program, including functions, special symbols, and identifiers Explore simple data types and examine the string data type Discover how to use arithmetic operators

Télécharger la présentation

CHAPTER 2 BASIC ELEMENTS OF C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CHAPTER 2BASIC ELEMENTS OF C++

  2. In this chapter, you will: • Become familiar with the basic components of a C++ program, including functions, special symbols, and identifiers • Explore simple data types and examine the string data type • Discover how to use arithmetic operators • Examine how a program evaluates arithmetic expressions • Learn what an assignment statement is and what it does • Discover how to input data into memory using input statements • Become familiar with the use of increment and decrement operators • Examine ways to output results using output statements • Learn how to use preprocessor directives and why they are necessary • Explore how to properly structure a program, including using comments to document a program • Learn how to write a C++ program

  3. A computer program or a program is a sequence of statements whose objective is to accomplish some task. • Programming is a process of planning and creating a program. • Cooking Recipe • It is usually easier to follow a recipe than to create one. • There are good recipes and there are bad recipes. • There are recipes which are easy to follow and there are those which are not. • There are recipes whose end results are reliable and there are those that are not. • One must have some knowledge of how to use cooking tools to follow a recipe to completion. • The same is true about programming

  4. The Basics of a C++ Program • A C++ program is a collection of one or more subprograms, called functions. • Roughly speaking, a subprogram or a function (like a program) is a collection of statements and when it is activated (that is, executed) it accomplishes something. • Every C++ program has a function called main.

  5. Example 2-1 #include <iostream> using namespace std; int main() { cout<<"Welcome to C++ Programming"<<endl; return 0; } Output: Welcome to C++ Programming

  6. To write meaningful programs, we learn the special symbols, words, and the syntax rules of the programming language. • The syntax rules tell us which statements (instructions) are legal, that is, accepted by the programming language and which are not. • Programming Language: A set of rules, symbols, and special words. • Semantic- The semantic rules determine the meaning of the instructions. • Metalanguage- A language used to write the syntax rules.

  7. Syntax template of the function main is: int main() { statement1 . . . statementn return 0; } • In these slides, reddish color indicate a part of the syntax that may or may not appear.

  8. The smallest individual unit of a program written in any language is called a token. Special-Symbols • The following are some of the special symbols + - * / . ; ? , <= != == >= Word-symbols int, float, double, char,void, return • These are called reservedwords, or keywords.

  9. Identifier Identifier: A C++ identifier consists of letters, digits, and the under score character (_), and must begin with a letter or underscore. • C++ is case sensitive—uppercase and lower case letters are different. • Some of the predefined identifiers are cout and cin. • Unlike reserved words, pre-defined identifiers may be redefined, but it would not be wise to do so.

  10. Example 2-2 The following are legal identifiers in C++. first conversion payRate counter1

  11. Data Types and Arithmetic Operators Data Type: A set of values together with a set of operations is called a data type. C++ data types fall into three categories • Simple Data Type. • Structured Data Type. • Pointers.

  12. Simple Data Type C++ simple data can be classified into three categories 1. Integral, which is a data type that deals with integers, or numbers without a decimal part. 2. Floating-point, which is a data type that deals with decimal numbers. 3. Enumeration type, which is a user-defined data type.

  13. Integral data types

  14. int Data Type -6728, -67, 0, 78, 36782, +763,... • Positive integers do not have to have a + sign in front of them. • No commas are used within an integer. • In C++ commas are reserved for separating items in a list. So 36,782 would be interpreted as two integers 36 and 782.

  15. The bool Data Type • The data type bool has two values, true and false. The central purpose of this data type is to manipulate logical (Boolean) expressions. We call true and false the logical (Boolean) values. • In C++, bool, true, and false are reserved words.

  16. char Data Type • char is the smallest integral data type. • char data type is used to represent characters, that is letters, digits and special symbols. • Each character is enclosed within single quote marks. Some of the values belonging to char data type are: 'A', 'a', '0', '*', '+', '$', '&' • Blank space is a character and is written '', with a space left between the single quotes.

  17. The Most Common Character Sets: • ASCII (American Standard Code for Information Interchange) and EBCIDIC. • The ASCII character set has 128 values. • EBCIDIC has 256 values and is used by IBM.

  18. ASCII Character Set • Each of the 128 values of the ASCII character set represents a different character. • The value 65 represents 'A', and the value 43 represents '+'. • Each character has a pre-defined ordering, which is called a collating sequence, in the set. • The collating sequence is used when you compare characters. • The value representing 'B' is 66, so 'A' is smaller than 'B'. • '+' is smaller than 'A' since 43 is smaller than 65. • The first 32 characters in the ASCII character set are nonprintable. • The 14th character in the set is the new line character. • In C++, the new line character is represented as '\n'. • The horizontal tab character is represented in C++ as '\t'. • The null character is represented as '\0'.

  19. ASCII (American Standard Code for Information Interchange) Ascii 0 1 2 3 4 5 6 7 8 9 0 nul soh stx etx eot enq ack bel bs ht 1 lf vt ff cr so si del dc1 dc2 dc3 2 dc4 nak syn etb can em sub esc fs gs 3 rs us b ! “ # $ % & ‘ 4 ( ) * + , - . / 0 1 5 2 3 4 5 6 7 8 9 : ; 6 < = > ? @ A B C D E 7 F G H I J K L M N O 8 P Q R S T U V W X Y 9 Z [ \ ] ^ _ ` a b c 10 d e f g h i j k l m 11 n o p q r s t u v w 12 x y z { | } ~ del

  20. Floating-Point Data Types • Scientific notation 43872918 = 4.3872918 *10^7 {10 to the power of seven}, .0000265 = 2.65 * 10^(-5) {10 to the power of minus five}, 47.9832 = 4.7983 * 10^1 {10 to the power of one} • To represent real numbers C++ uses scientific notation called floating-pointnotation.

  21. float: The data type floatis used in C++ to represent any real number between -3.4E+38 and 3.4E+38.The memory allocated for the floatdata type is 4 bytes. double: The data type doubleis used in C++ to represent any real number between -1.7E+308 and 1.7E+308.The memory allocated for the doubledata type is 8 bytes. • On most newer compilers, the data typesdoubleandlong doubleare the same.

  22. The maximum number of significant digits—that is, the number of decimal places—in floatvalues is 6 or 7. • The maximum number of significant digits in values belonging to the doubletype is 15. • The maximum number of significant digits is called the precision. • floatvalues are called single precision • double values are called double precision. 2

  23. The string Type • The data type string is a programmer-defined type and is not part of the C++ language. The C++ standard library supplies it. • A string is a sequence of zero or more characters. • Strings in C++ are enclosed in double quote marks. • A string with no characters is called a null or empty string. "William Jacob" “Mickey" "” • "" is the empty string. • Every character in a string has a relative position in the string. • The position of the first character is 0, position of the second character is 1, and so on. • The length of a string is the number of characters in it.

  24. Example 2-3 String Position of a Character Length of the String in the Sting "William Jacob" Position of 'W' is 0. 13 Position of the first 'i' is 1. Position of ' ' (the space) is 7. Position of 'J' is 8. Position of 'b' is 12. “Mickey" Position of ‘M' is 0. 6 Position of 'i' is 1. Position of 'c' is 2. Position of 'k' is 3. Position of 'e' is 4. Position of 'y' is 5.

  25. ARITHMETIC OPERATORS AND OPERATOR PRECEDENCE • Arithmetic Operators + addition - subtraction * multiplication / division % remainder (mod operator) • The operators +, -, *, and / can be used with both integral and floating point data types, while % is used only for integral data type to find the remainder in ordinary division.

  26. Arithmetic Expressions 3 + 4 2 + 3 * 5 5.6 + 6.2 * 3 x + 2 * 5 + 6 / y x and y are some unknown numbers • 2

  27. Unary operator: An operator that has only one operand. • Binary Operator: An operator that two operands. In the expression –5 – has only one operand, which is 5 and so - acts as a unary operator. In the expression +27 + is a unary operator.

  28. Further, in the expressions 3 + 4 23 - 45 both the operators + and – are binary operators. • – and + are both unary as well as binary arithmetic operators. • *, /, and % are binary arithmetic operators.

  29. Example 2-4 Arithmetic Expression Result Description 2 + 5 7 13 + 89 102 34 - 20 14 45 - 90 -45 2 * 7 14 5/2 2 In the division 5/2, the quotient is 2 and the remainder is 1. Therefore, 5/2 evaluates to the quotient, which is 2. 14 / 7 2

  30. 34 % 5 4 In the division 34/5, the quotient is 6 and the remainder is 4. Therefore, 34%5 evaluates to the remainder, which is 4 -34 % 5 -4 In the division -34 / 5, the quotient is -6 and the remainder is -4. Therefore, -34 % 5 evaluates to the remainder, which is -4. 34 % -5 4 In the division 34 / -5, the quotient is –6 and the remainder is 4. Therefore 34 % -5 evaluates to the remainder, which is 4.)

  31. -34 % -5 -4 In the division -34 / -5, the quotient is 6 and the remainder is -4. Therefore, -34 % -5 evaluates to the remainder, which is -4.) 4 % 6 4 In the division 4/6, the quotient is 0 and the remainder is 4. Now 4 % 6 evaluates to the remainder, which is 4.

  32. Example 2-5 Expression Result 5.0 + 3.5 8.5 3.0 + 9.4 12.4 16.3 - 5.2 11.1 4.2 * 2.5 10.50 5.0/2.0 2.5

  33. Order of Precedence The precedence rules of arithmetic operators are: *, /, % are at a higher level of precedence than + , - • Operators *, /, and % have the same level of precedence. • Operators + and - have the same level of precedence.

  34. When operators are all on the same level, they are performed from left to right. • To avoid confusion, the grouping symbol can be used. For example, 3*7-6+2*5/4+6 means (3 * 7) - 6 + ( ( 2 * 5) / 4 ) + 6 = 21 - 6 + (10 / 4) + 6 (Evaluate *) = 21 – 6 + 2 + 6 (Evaluate /) = 15 + 2 + 6 (Evaluate -) = 17 + 6 (Evaluate first +) = 23 (Evaluate +)

  35. Character Arithmetic • 8+7 = 15 • '8' + '7' = 56 + 55 = 111 • '8' + 7 = 56 + 7 = 63 • '8' * '7' is undefined in the ASCII character data set.

  36. EXPRESSIONS • If all operands (that is, numbers) in an expression are integers, the expression is called an integral expression. • If all operands in an expression are floating-point numbers, the expression is called a floating-point or decimalexpression. • An integral expression yields an integral result; a floating-point expression yields a floating-point result.

  37. Example 2-7 Some C++ integral expressions: 2 + 3 * 5 3 + x - y / 7 x + 2 * (y - z) + 18 Example 2-8 Some C++ floating point expressions: 12.8 * 17.5 - 34.50 x * 10.5 + y - 16.2

  38. Mixed Expressions • An expression that has operands of different data types is called a mixed expression. • A mixed expression contains both integers and floating-point numbers. Examples of mixed expressions 2 + 3.5 6 / 4 + 3.9 5.4 * 2 – 13.6 + 18 / 2

  39. Rules to evaluate a mixed expression 1. When evaluating an operator in the mixed expression: a. If the operator has the same types of operands (that is, either both integers or both floating-point numbers), the operator is evaluated according to the type of the operands. b. If the operator has both types of operands (that is, one is an integer and the other is a floating-point number) then during calculation the integer is changed to a floating-point number with the decimal part of zero and the operator is evaluated. The result is a floating-point number. 2. The entire expression is evaluated according to the precedence rules; the multiplication, division, and modulus operators are evaluated before the addition and subtraction operators. Operators having the same level of precedence are evaluated from left to right. Grouping is allowed for clarity.

  40. Example 2-9 (a) 3 / 2 + 5.0 = 1 + 5.0 (3 / 2 = 1) = 6.0 (1 + 5.0 = 1.0 + 5.0= 6.0) (b) 15.6 / 2 + 5 = 7.8 + 5 (15.6 / 2 = 15.6 / 2.0 = 7.8) = 12.8 (7.8 + 5.0 = 12.8) (c) 4 * 3 + 7 / 5 – 25.6 = 12 + 7 / 5 – 25.6 (4 * 3 = 12) = 12 + 1 – 25.6 (7 / 5 = 1) = 13 – 25.6 (12 + 1 = 13) = -12.6 (13 – 25.6 = 13.0 – 25.6 = - 12.6)

  41. Implicit Type Coercion • Cast operator (type conversion or type casting) Syntax Cast operator static_cast<dataTypeName>(expression) • Expression is evaluated and its value is converted to value of the type specified by the dataTypeName.

  42. Example 2-10 static_cast<int>(7.9) = 7 static_cast<int>(3.3) = 3 static_cast<double>(25) = 25.0 static_cast<double>(5+3) = static_cast<double>(8) = 8.0 static_cast<double>(15)/2 = 15.0/2 = 15.0/2.0 = 7.5

  43. static_cast<double>(15/2) = static_cast<double>(7) = 7.0 static_cast<int>(7.8 + static_cast<double>(15)/2) = static_cast<int>(7.8 + 7.5) = static_cast<int>(15.3)= 15 static_cast<int>(7.8 + static_cast<double>(15/2) = static_cast<int>(7.8 + 7.0) = static_cast<int>(14.8)= 14

  44. x = 15 y = 23 z = 3.75 Expression Value static_cast<int>(7.9 + 6.7)14 static_cast<int>(7.9) + static_cast<int>(6.7) 13 static_cast<double>(y / x) + z 4.75 static_cast<double>(y) / x + z 5.28333

  45. INPUT Storing data in the computer’s memory is a two step process. • Instruct the computer to allocate memory. • Include statements in the program to put data into the allocated memory.

  46. Allocating Memory with Constants and Variables • Named Constant: A memory location whose content is not allowed to change during program execution. • Variable: A memory location whose content may change during program execution.

  47. Named Constant: The syntax to declare a named constant is const dataType identifier = value; • In C++,constis a reserved word. Example 2-11 constdouble conversion = 2.54; constint noOfStudents = 20; constchar blank = ' '; constdouble payRate = 15.75;

  48. Variable The syntax for declaring one variable or multiple variables is dataType identifier, identifier, . . .; Example 2-12 double amountDue; int counter; char ch; int x, y; string name;

  49. 1. In C++, all identifiers must be declared before they can be used. If we refer to an identifier without declaring it, the compiler will generate an error message indicating that the identifier is not declared. 2. A data type is called simple if the variable (or named constant) of that type can store only one value at a time. For example, if x is an, say, int variable. Then at a given time only one value can be stored in x.

More Related