Chapter 2 Basic Elements of C++

advertisement
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
 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
Example 2-1
#include <iostream>
using namespace std;
int main()
{
cout<<"Welcome to C++ Programming"<<endl;
return 0;
}
Output:
Welcome to C++ Programming
 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 reserved words, or keywords. (p.1033)
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.
•Example 2-2
The following are legal identifiers in C++.
First conversion payRate counter1
Integral data types
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.
ASCII Character Set - p.1037
 Each of the 128 values of the ASCII character set represents a
different character.
 The value 65 represents 'A', and the value 43 represents '+'.
 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'.
Floating-Point Data Types
• Scientific notation
43872918 = 4.3872918 *10^7
.0000265 = 2.65 * 10^(-5)
five},
47.9832 = 4.7983 * 10^1
{10 to the power of seven},
{10 to the power of minus
{10 to the power of one}
• To represent real numbers C++ uses scientific notation called
floating-point notation.
float: The data type float is used in C++ to represent any real number
between -3.4E+38 and 3.4E+38.The memory allocated for the float data
type is 4 bytes.
double: The data type double is used in C++ to represent any real number
between -1.7E+308 and 1.7E+308.The memory allocated for the double
data type is 8 bytes.
On most newer compilers, the data types double and long double are the
same.
 The maximum number of significant digits—that is, the number of decimal
places—in float values is 6 or 7.
 The maximum number of significant digits in values belonging to the
double type is 15.
 The maximum number of significant digits is called the precision.
 float values are called single precision
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
in the Sting
"William Jacob" Position of 'W' is 0.
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
Position of
Position of
Position of
Position of
Position of
‘M'
'i'
'c'
'k'
'e'
'y'
is
is
is
is
is
is
0.
1.
2.
3.
4.
5.
Length of the String
13
6
ARITHMETIC OPERATORS AND OPERATOR
PRECEDENCE
• Arithmetic Operators
+
*
/
%
addition
subtraction
multiplication
division
remainder (mod operator)
• Arithmetic Expressions
3 + 4
2 + 3 * 5
5.6 + 6.2 * 3
x + 2 * 5 + 6 / y
x and y are some unknown numbers
• 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.
Example 2-4
Arithmetic
Expression
2 + 5
45 - 90
2 * 7
5/2
Result
7
-45
14
2
34 % 5
4
5.0 + 3.5
5.0/2.0
Description
In the division 5/2, the quotient is
2
In the division 34/5, the quotient is 6 and
the remainder is 4.
8.5
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,
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 decimal expression.
• An integral expression yields an integral result; a floating-point
expression yields a floating-point result.
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
Example 2-9
(a) 3 / 2 + 5.0
= 1 + 5.0
= 6.0
(3 / 2 = 1)
(1 + 5.0 = 1.0 + 5.0= 6.0)
(b) 15.6 / 2 + 5
= 7.8 + 5
= 12.8
(15.6 / 2 = 15.6 / 2.0 = 7.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
 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<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<int>(7.8 + static_cast<double>(15)/2)
= static_cast<int>(7.8 + 7.5)
= static_cast<int>(15.3)
= 15
Variable
The syntax for declaring one variable or multiple variables is
dataType identifier, identifier, . . .;
•Example 2-12
int
counter;
char
ch;
int
x, y;
string name;
Named Constant: The syntax to declare a named constant is
const dataType identifier = value;
• In C++, const is a reserved word.
•Example 2-11
const int noOfStudents = 20;
const char blank = ' ';
const string str = "It is a sunny day. ";
Declaration and Initializing Variables
 Variables can be initialized when they are declared
int first, second;
char ch;
double x, y;
first = 13;
second = 10;
ch = ' ';
x = 12.6;
y = 123.456;
Equivalently, we can write the following C++ statements.
int first=13, second=10;
char ch=' ';
double x=12.6, y=123.456;
Input (Read) Statement
Syntax of cin together with >>:
cin>>variable>>variable. . .;
 In C++, >> is called the extraction operator.
 Suppose miles is a variable of the type double.
cin>>miles;
 By using more than one variable in cin, more than one value can be read at a
time.
Suppose feet and inch are variables of the type int. A statement like
cin>>feet>>inch;
INCREMENT AND DECREMENT OPERATORS
Increment operator - increment the value of a variable by 1
Decrement operator- decrement the value of a variable by 1.
Pre Increment:
Post Increment:
++variable
variable++
++count;
or
count++;
increments the value of count by 1.
Pre Decrement:
Post Decrement:
--variable
variable--
--count;
or
count--;
decrements the value of count by 1.
1.
x = 5;
y = ++x;
• After the second statement both x and y are 6.
2.
x = 5;
y = x++;
• After the second statement y is 5 and x is 6.
Example 2-16
Suppose a and b are int variables.
a = 5;
b = 2 + (++a);
After the second statement a is 6 and b is 8.
OUTPUT
 The syntax of cout together with << is
cout<<expression or manipulator<<expression or
manipulator...;
 In C++, << is called the insertion operator.
 expression (that is, expression) is evaluated and its value is
printed at the current cursor position on the screen.
 manipulator manipulates the output. The simplest
manipulator is endl (the last character is the letter el), which
causes the cursor to move to the beginning of the next line.
 This is called an output statement. Sometimes this is also called a
cout statement.
 In C++, << is called the stream insertion operator.
 Strings and expressions involving only one variable or a single
value are evaluated to itself.
• \n is called new line escape sequence.
• \ (back slash) is called the escape character.
Example 2-18
int a, b, c, d;
a = 65 ;
b = 78 ;
cout<<29/4<<endl;
cout<<3.0/2<<endl;
cout<<"Hello there.\n";
cout<<"a"<<endl;
cout<<b<<‘\n’;
cout << endl;
7
1.5
Hello there.
65
78
•The following statement is illegal in C++.
cout<<"It is sunny, warm, and not a windy day.
Let us go golfing."<<endl;
cout<<"The newline escape sequence is \\n"<<endl;
The new line escape sequence is \n
cout<<"The tab character is represented as \'\\t\'"<<endl;
The tab character is represented as '\t'
cout<<"The string \"Sunny\" contains five characters\n";
The string "Sunny" contains five characters
Preprocessor Directives
 Only a small number of operations are explicitly defined in C++.
 Many of the functions and symbols that are necessary to run a C++
program are provided as a collection of libraries.
 Every library has a name and is referred as a header file. For
example, the descriptions of the functions needed to perform I/O are
contained in the header file iostream.
 The descriptions of some very useful mathematics functions such as
power, absolute, sine, etc., are contained in the header file cmath.
 Preprocessor directives are commands supplied to the preprocessor.
 All preprocessor commands begin with #.
 There is no semicolon at the end of these commands since these are
preprocessor commands not C++ commands.
#include <cmath>
#include <iostream>
#include <string>
Using cin and cout in a Program and namespace
• One way to use cin and cout in a program is to refer them as
std::cin and std::cout.
• Another option is to include the following statement in your program:
using namespace std;
• The using statement appears after the statement
#include <iostream>.
Documentation
Comments
• Single line comments
• Single line comments begin with // anywhere in the line.
• Multiple line comments.
• Multiple line comments are enclosed between /* and */.
Prompt Lines
cout<<"Please enter a number between 1 and 10 and"
<<" press the return key"<<endl;
cin>>num;
When these two statements execute in the order given, first the cout
statement causes the following line of text to appear on the screen:
Please enter a number between 1 and 10 and press the
return key
After seeing this line, users know that they must enter a number and
press the return key.
Compound assignment operator
op=
where op is any of the arithmetic operators.
• Using the compound assignment operator, the simple assignment
statement
variable = variable op (expression);
can be rewritten as
variable op= expression;
and is called the compound assignment statement.
I = I + 5;
I += 5;
Download