Create Presentation
Download Presentation

Download Presentation
## CHAPTER 2 BASIC ELEMENTS OF C++

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -

**The Basics of a C++ Program**• 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. • 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.**Example 2-1**#include <iostream> using namespace std; int main() { cout<<"Welcome to C++ Programming"<<endl; return 0; } Output: Welcome to C++ Programming**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.**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.**The smallest individual unit of a program written in any**language is called a token. • Tokens: Special symbols, word symbols, identifiers Special-Symbols • The following are some of the special symbols + - * / . ; ? , <= != == >= Word-symbols int, float, double, char,void, return • These are called reservedwords, or keywords.**Identifier**Identifier: A C++ identifier consists of letters, digits, and the under score character (_), and must begin with a letter or underscore. Identifiers are the names of things that appear in programs, such as variables, constants, and functions. • 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.**Example 2-2**The following are legal identifiers in C++. first conversion payRate counter1**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.**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.**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.**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.**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.**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.**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'.**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**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.**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.**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**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.**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.**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.**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**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.**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.**Example 2-4**Arithmetic (Assume integral data types) 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**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.)**-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.**Example 2-5**Assume floating-point numbers 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**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.**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 +)**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.**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.**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**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**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.**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)**Implicit Type Coercion**When evaluating an arithmetic expression if the operator has mixed operands, the integer value is changed to floating-point values with zero decimal part. This action is called an implicit type of 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.**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**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**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**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.**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.**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;**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;**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.**Putting Data into Variables**• In C++ there are two ways that data can be placed into a variable: 1. Using C++’s assignment statement, and 2. Use input (read) statements.**Assignment Statement**The assignment statement takes the form variable = expression; • The expression is evaluated and its value is assigned to the variable on the left side. • In C++, = is called the assignment operator.