Chapter 7 Introduction To C++
Chapter 7 Introduction To C++
CHAPTER 7
Introduction to C++
OBJECTIVES
To Understand the basic features of C++ as a OPP language/
145
146
Introduction to C++
147
Introduction to C++
Portability: We can practically compile the same C++ code in almost any type of computer
and operating system without making any changes. C++ is the most used and ported programming
language in the world.
Brevity: Code written in C++ is very short in comparison with other languages, since the use of
special characters is preferred to key words, saving some effort to the programmer (and
prolonging the life of our keyboards!).
Modular programming: An application’s body in C++ can be made up of several source code
files that are compiled separately and then linked together saving time, since it is not necessary to
recompile the complete application when making a single change, but only in the file that contains
it. In addition, this characteristic allows to link C++ code with code produced in other languages,
such as Assembler or C.
C Compatibility: C++ is backward compatible with the C language. Any code written in C can
easily be included in a C++ program without making any change.
Speed: The resulting code from a C++ compilation is very efficient due to its duality as high-
level and low-level language and to the reduced size of the language itself.
Machine independent: It is a Machine Independent Language.
Flexibility: It is highly flexible language with Versatility.
Wide range of library functions: It has huge Library Functions which in turn reduces the code
development time and also reduces cost of software development.
System Software development: It can be used for developing System Software viz., operating
systems, compilers, editors and data bases.
The most fundamental elements of a C++ program are “tokens” or lexical elements. These elements
help us to construct statements, definitions, declarations, and so on, which in turn helps us to construct
148
Introduction to C++
complete programs. Indeed, all the programming languages are made up of these individual syntax ele-
ments called
eÁw
tokens .C++ has following tokens.
Identifiers
Keywords
Constants or Literals
Punctuators
Operators
7.3.1 Identifiers
An identifier is a name given to the programming elements such as variables, arrays, functions etc. It can
contain letter, digits and underscore. C++ is case sensitive and henceforth it treats uppercase and
lowercase characters differently.
Identifiers are the names given to program elements (program elements include variables, arrays,
functions, etc.). It is important to note that C++ is case sensitive and it treats uppercase and lowercase
characters differently. The following are some of the valid identifiers in C++.
Student _amount marks1 total_ score
STUDENT _AMOUNT RANK5 _Ad12
The following are some of the invalid identifiers:
34data - starts with a digit
reg-no - contains a special character ‘-‘
public - reserved word
Therefore, we can summarize the rules for naming an identifier as
Identifiers are a sequence of characters which should begin with the alphabet either from
A-Z (uppercase) or a-z (lowercase) or _(underscore).
C++ treats uppercase and lowercase characters differently.
For example, DATA is not same as data.
No special character is allowed except _ (underscore).
A keyword cannot be used for naming an identifier.
Identifiers should be of reasonable length (but ANSI C has not enforced any restriction on
this aspect).
C++ treats uppercase and lowercase differently. But we can use the keywords in uppercase as identifiers,
since the complier considers while, if etc. as keywords. But it does not consider the same words in
uppercase i.e., WHILE, IF etc. as identifiers. However it is not treated as a good programming practice
to make use of keywords as identifiers.
149
Introduction to C++
7.3.2 Keywords
Keyword is a predefined word that gives special meaning to the compiler. They are reserved words
which can be used for their intended purpose and should not be used as normal identifier. There are
keywords in C++ (developed by Stroustrup) as mentioned in Table7.1.
alignas (since C++11) enum return
alignof (since C++11) explicit short
and export signed
and_eq extern sizeof
asm false static
auto(1) float static_assert(since C++11)
bitand for static_cast
bitor friend struct
bool goto switch
break if template
case inline this
catch int thread_local(since C++11)
char long throw
char16_t(since C++11) mutable true
char32_t(since C++11) namespace try
class new typedef
compl noexcept(since C++11) typeid
const not typename
constexpr(since C++11) not_eq union
const_cast nullptr (since C++11) unsigned
continue operator using(1)
decltype(since C++11) or virtual
default(1) or_eq void
delete(1) private volatile
do protected wchar_t
double public while
dynamic_cast register xor
else reinterpret_cast xor_eq
Table7.1 Keywords NOTE: In Table 7.1 (since C++11)means revised in the year 2011.
Keyword is a predefined word and has special meaning to the compiler. The programmer is not allowed
to change its meaning,
150
Introduction to C++
Invariant program elements are called “literals” or “constants.” The terms “literal” and “constant” are
used interchangeably.Figure7.2
eÁw
shows the clear classification of literals. They are program elements whose
value does not change during program execution. A literal may be any of the following:
Integer constant
Floating constant
Character constant
String literal
Constant is a fixed value that does not change during the execution of the program.
Example 7.1:
int a = 1587; // Decimal constant
int b = -148; // A negative decimal constant
int c = 065; // Leading zero specifies octal constant, not decimal
151
Introduction to C++
Octal constant:
When we specify an octal constant, we should always begin with 0 followed by a sequence of digits
in the range 0 through 7. The digits 8 and 9 are errors in specifying an octal constant.
Example 7.2:
int a = 0374; // Octal constant
int j = 095; // Error: 9 is not an octal digit
Hexadecimal constants:
When we specify a hexadecimal constant, we should always begin the specification with 0x or 0X
(the case of the “x” does not matter), followed by a sequence of digits in the range 0 through 9 and a (or
A) through f (or F). Hexadecimal digits a (orA) through f(or F) represents values in the range 10 through
15.
Example 7.3:
int a = 0x5fff; // Hexadecimal constant
int b = -0X3FFF;
Unsigned constants:
To specify an unsigned type, use either the u or U suffix. To specify a long type, use either the l or L
suffix.
Example 7.4:
unsigned val= 328u; // Unsigned value
long val= 0x7FFFFFL; // Long value specified as hex constant
unsigned long val = 0776745ul; // Unsigned long value as octal constant
152
Introduction to C++
Example 7.5
eÁw
18 . 45
The exponent, if present, specifies the magnitude of the number as a power of 10, as shown in the
following example 7.6.
Example 7.6
23.46e0 // means it is equal to 23.46 x 100 = 23.46 x 1 = 23.46
23.46e1 // means it is equal to23.46 x 101= 23.46 x10 = 234.6
23.46e-1 // means it is equal to23.46 x 10-1= 23.46 x1/10 =2.346
- 0.2346e-1 // means it is equal to -0.2346 x 10-1= -0.2346x 1/10= -0.02346
The exponent may be specified using e or E, which have the same meaning, followed by an
optional sign (+ or -) and a sequence of digits. If an exponent is present, the trailing decimal point is
unnecessary in whole numbers such as 23E0.
Floating-point constants default to type double. By using the suffixes f or l (or F or L — the
suffix is not case sensitive), the constant can be specified as float or long double, respectively.
A single character constant such as ‘D’ or ‘r’ will have char data type. These character
constants will be assigned numerical values. The numerical values are the ASCII values which are
numbered sequentially for both uppercase and lowercase characters. For example, ASCII value of A is
65, B is 66,….,Z is 90 (uppercase characters), a is 97, b is 99,….z is 122 (lowercase characters), 0 is
48, 1 is 49,…9 is 57 (for digits). Indeed all the characters on the keyboard are assigned with an ASCII
value.
There is another class of characters which cannot be displayed on the screen (non-graphic characters)
but they have special meaning and are used for special purpose. For example, tab key, carriage return,
backspace and such character constants are called as escape sequences. The following table7.2 shows
the list of escape sequences in C++.
153
Introduction to C++
Escape Description
sequence
\’ single quote
\” double quote
\? question mark
\\ backslash
\0 null character
\a audible bell
\b backspace
\f form feed - new page
\n line feed - new line
\r carriage return
\t horizontal tab
\v vertical tab
\nnn arbitrary octal value
\xnn arbitrary hexadecimal value
Table 7.2 Escape sequences in C++
Escape sequence is a special string used to control output on the monitor and they are represented by
a single character and hence occupy one byte space.
7.3.4 Punctuators
Punctuators in C++ have syntactic and semantic meaning to the compiler but do not by themselves
specify an operation that yields a value. Some punctuators can be either alone or in combination, and they
can be significant to the preprocessor. The following characters are considered as punctuators:
! % ^ &* ( ) – + = { } | ~
[ ] \ ; ‘ : “<> ? , . / #
154
Introduction to C++
The functions of some of the punctuators is given in the below table 7.3.
eÁw
symbols Illustration
! used along with ‘=’ to indicate ‘not equal to’
% used along with format specifier
& used to represent address location or bitwise and operation
; used to represent statement terminator
[] used to represent array subscript
{} used to represent the starting and ending of a block of code
() used to represent function calls, group expressions, etc.
# used to represent preprocessor directive
\ used to represent escape sequence
Operator Name
155
Introduction to C++
Operator Name
In C++, it becomes absolutely necessary to understand about the increment and decrement operators
under unary operators and they operate on a single variable.++ is used to increment the value of the
variable by 1 and the operator can appear before or after the variable and — is used to represent
decrement the value of the operator by 1. Just like the increment operator the decrement operator can
also appear before or after the variable as shown below. Therefore,
a++ or ++a means a=a+1
b— or —b means b=b-1
If the ++/— operator is to the left of the variable then, it is called pre- increment/decrement operator
and if the ++/— operator is to the right of the variable then, it is called post increment/decrement operator.
However, in both the cases of incrementing and decrementing there will be significant change in their
values during the course of the program execution.
Consider the following statements in a program:
int a = 5,b;
…..
b = ++a;
b = a++;
In the first statement, the value of b will be 6 and in the second statement the value of b will be
still 6 and not 7 because in case of post incrementing the value is considered first and then incremented.
b = a++;
156
Introduction to C++
then, the value of b will be still 6 and not 7 because the operator is to the right of the variable
considers
eÁw
the value and then increments it.
157
Introduction to C++
> Checks if the value of left operand is greater than (a > b) is false.
the value of right operand.
< Checks if the value of left operand is less than the (a < b) is true.
value of right operand.
>= Checks if the value of left operand is greater than (a >= b) is false.
or equal to the value of right operand.
<= Checks if the value of left operand is less than or a <= b) is true.
equal to the value of right operand.
158
Introduction to C++
Example 7.8:
Assume that if a = 60; and b = 13; the following operations takes place:
Step 1: converts a and b both to its binary equivalent.
a = 0011 1100
b = 0000 1101
Step 2: then performs the bitwise and, or and not operations. The result is given below.
a&b = 0000 1100 (bitwise and) = 12
a|b = 0011 1101 (bitwise or) = 61
a^b = 0011 0001 (bitwise xor) = 49
~a = 1100 0011 (bitwise not) = -60
159
Introduction to C++
The Bitwise operators supported by C++ are listed in the following table 7.9.
^ Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49 which is
operand but not both. 0011 0001
~ Binary Ones Complement Operator is unary and has the (~A ) will give -60 which is
effect of ‘flipping’ bits. 1100 0011
<< Binary Left Shift Operator. The left operands value is A << 2 will give 240 which
moved left by the number of bits specified by the right is 1111 0000
operand.
>> Binary Right Shift Operator. The left operands value is A >> 2 will give 15 which is
moved right by the number of bits specified by the right 0000 1111
operand.
Table7.9 Bitwise Operators
All assignment operators have lower precedence than the conditional operator (?).
160
Introduction to C++
161
Introduction to C++
Operator Description
sizeof () sizeof operator returns the size of a variable. For example
sizeof(a), where a is integer, will return 2.
Comma operator causes a sequence of operations to be
, performed. The value of the entire comma expression is the value
of the last expression of the comma-separated list.
. (dot) and -> (arrow) Member operators used to reference individual members of
classes, structures, and unions.
cast Casting operators convert one data type to another. For example,
int(2.2000) would return 2.
Operator Description
? Conditional operator. If condition is true, expression in the TRUE
is selected, otherwise the expression in the FALE part is selected.
Table7.12 Ternary Operator
162
Introduction to C++
The operator that operates on three operands is called the conditional operator or ternary
operator.
eÁw
If the expression contains multiple operators, the order in which operations are carried out is
called precedence of operators. It is also called as priority or hierarchy.
Example 7.9: x = 7 + 3 * 2;
Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get
multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table and those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first. The
precedence of operators along with its associativity is given in the below table 7.13.
163
Introduction to C++
The expression in parenthesis is evaluated first. In case of nested parenthesis the part of
expression in the inner most parenthesis is evaluated first. Next, multiplication and division operators are
evaluated. Then, plus and minus operators are evaluated. Relational operators, Logical AND, OR,
NOT and finally the assignment operator are respectively evaluated.
164
Introduction to C++
If the expression contains the operators of equal priority then the operations are performed as first-
come-first-serve
eÁw
basis.
165
Introduction to C++
Here, the value of a has been promoted from short to int and we have not had to specify any type-
casting operator. This is known as a standard conversion. Standard conversions affect fundamental data
types, and allow conversions such as the conversions between numerical types (short to int, int to float,
double to int...), to or from Boolean, and some pointer conversions. Some of these conversions may
imply a loss of precision, which the compiler can signal with a warning. For example,
Here in the above example, the compiler will most likely generate a warning about truncation as
trying to put a large number into a small variable will lose part of the number’. The compiler will make
numbers bigger (never smaller) when evaluating expressions. If you add a float to a double, it will treat
both as doubles. Add an int to a float and both are treated as floats. Add a short int to an int and both will
be added as int, and the same is true with char. For example,
char a = '2';
int b = a + 9;
This is poor code but it compiles and runs. The implicit promotion of ‘2’ to an int with a value of 50
results in it outputting 59.this is because the compiler considers the ASCII value of ‘2’ which is 50 and
therefore it outputs 59. This can be avoided with an explicit conversion.
short a = 2000;
int b;
b = (int) a; // c-like cast notation
b = int (a); // functional notation
Implicit conversion will be performed by the compiler itself, without user intervention. Explicit
conversion will be performed by the user, as his need.
166
Introduction to C++
#include<iostream.h>
void main()
{
cout<<"This is first C++ program";
}
The above program contains certain basic elements that all C++ programs possess. In The next
section, we will be able to understand in depth about the actual structure of a C++ program.
167
Introduction to C++
Let us understand each section one by one in detail by considering the above figure 7.4.
Linker Section
#include<iostream.h>
#include<conio.h>
The linker section begins with a hash (#) symbol and #include…. is a preprocessor directive and
these statements are processed first by the compiler and then the rest of the statements are
compiled. These statements tells the compiler to include the header files iostream.h and conio.h into the
program.
168
Introduction to C++
Definition Section
eÁw #define PI 3.14
In this section, we can define constants, expressions, structures, functions, classes and objects. After
the linker section gets executed, the definition section is executed by the compiler and this section is
optional. In the above example, we find that PI is a constant identifier which takes the value 3.14 and
wherever this identifier is used the compiler replaces the value with 3.14 in the program.
main ( ) function
void main( )
This instruction marks the beginning of the main function and it contains the statements that perform
the required task. This statement is executed first by the compiler when the program starts. It is also
important to note that there will be only one main( ) function in a program.
Braces {}
{ Opening braces
…..
…..
…..
} Closing braces
The statements inside any function including the main ( ) function is enclosed with the opening and
closing braces. Therefore we find the { } in the above figure 7.4 also.
169
Introduction to C++
radius and the text present inside the double quotes “ input the value of radius: ” is displayed on the output
screen.
The next is thecin function statement which takes the input that is given by the user. The
next two statements are C++ expressions that calculate the area and circumference of the circle
respectively.
Finally, the next two output statements display the computed area and circumference
respectively.
#include directive
The #include directive instructs the compiler to read and include another file in the current file.
The compiler compiles the entire code. A header file may be included in one of two ways.
#include<iostream.h>
or
#include "iostream.h"
The header file in angle brackets means that file reside in standard include directory. The header files
in double quotes means that file reside in current directory.
170
Introduction to C++
log(x) logarithm of x
All of the trigonometric functions take double arguments and have double
return types.
The trigonometric functions work in radiansrather than degrees.
Radians =
171
Introduction to C++
Function Meaning
isalnum(c) It returns True if c is a digit from 0 through 9 or an alphabetic character (either upper
case or lowercase) otherwise False.
strcat(s1, s2) It concatenates the string s2 onto the end of the string s1. The string s1 must
have enough locations to hold s2.
strcpys(s1, s2) It copies character string s2 to string s1. The s1 must have enough storage
locations to hold s2.
strcmp((s1, s2)==0)
strcmp((s1, s2)>0) It compares s1 and s2 and finds out whether s1 equal to s2, s1 greater than
strcmp((s1, s2) <0) s2 or s1 less than s2.
strcmpi((s1, s2)==0) It compares s1 and s2 ignoring case and finds out whether s1 equal to s2,
strcmpi((s1, s2)>0) s1 greater than s2 or s1 less than s2.
strcmpi((s1, s2) <0)
172
Introduction to C++
getchar() It returns a single character from a standard input device (keyboard). It takes no
parameter and the returned value is the input character.
putchar() It takes one argument, which is the character to be sent to output device. It also returns
this character as a result.
gets() It gets a string terminated by a newline character from the standard input stream stdin.
puts() It takes a string which is to be sent to output device.
randomize() It initializes / seeds the random number generator with a random number
random(n) It generates a random number between o to n-1
atoi(s) It converts string s into a numerical representation.
itoa(n) It converts a number to a string
173
Introduction to C++
Review questions
One mark questions:
1. Who developed C++?
2. C++ is a subset of C. True or false?
3. Mention any two characteristics of C++.
4. Mention the characteristics of C++.
5. Define token.
6. Mention any two tokens of C++.
7. What is an identifier?
8. Keyword can be used to name an identifier. True/false
9. Mention any two keywords in C++.
10. What is a keyword?
11. What is a constant?
12. What is an integer constant?
13. What is an octal constant?
14. What is a hexadecimal constant?
15. Give an example for integer constant.
16. Give an example for octal constant.
17. Give an example for hexadecimal constant.
18. Give an example for float constant.
19. Give an example for character constant.
20. Give an example for string constant.
21. What are escape sequence?
22. Mention any two escape sequences.
23. What are punctuators?
24. Mention any two punctuators.
25. What is an operator?
26. What are unary operators?
27. Mention any two unary operators.
28. Give the output for the expression y=++x-x++ if x=10.
29. What are binary operators?
30. Mention any two binary operators.
31. Mention the operators supported by arithmetic operators.
32. Mention the operators supported by relational operators.
33. Mention the operators supported by logical operators.
34. Mention the operators supported by bitwise operators.
35. Give an example for assignment operators.
36. Give an example for sizeof operator.
174
Introduction to C++
175
Introduction to C++
176