c++lang chap2
TRANSCRIPT
-
8/11/2019 C++Lang chap2
1/12
CHAPTER 2
Basics of C++
2.1 C++ CHARACTER SETThere are two character sets in C++ language. These are:
(a) Source characters
(b) Execution characters/Escape sequences
2.1.1 Source Characters
Using source characters, the source text is created. Following is the list of source characters:
Alphabets A to Z, a to z and _ (underscore)
Decimals 0 to 9
Special characters + - * / ~ % = ! & | ( ) { } [ ] ? , ; : \ # blank "
2.1.2 Execution Characters/Escape SequencesThese characters are interpreted at the time of execution. The values of execution characters are
implementation-defined.
The characters on the keyboard can be printed or displayed by pressing the key. But some
characters such as line feed, form feed, tab, etc. cannot be printed or displayed directly. C++ pro-
vides the mechanism to get such characters that are invisible or difficult through execution char-
acters. Execution characters and escape sequences are used inter-changeably.
Each of the escape sequences shall produce a unique implementation-defined value which can
be stored in a single character. These escape sequences are represented by a backslash (\) followed
by a character. Though there are two characters in an escape sequence, they are considered as a
single character. Some of them are shown in the following Table 2.1.
Many other characters, after backslash (\), in output statements will result in display of the
character itself. For example, the execution of \k will result in display of k.
2.2 C++ TOKENS
The indivisible elements in a program line are calledtokens(see Figure 1.1). Each token should be
separated from the other by a space, tab or carriage return, which are collectively termed white
space. However, C++ recognizes some special tokens, such as parentheses, without imposing the
bpbonline all rights reserved
-
8/11/2019 C++Lang chap2
2/12
12 Programming in C++ Part I
need for any separating white space. For example return(0)is valid, even though white space
has been omitted between the reserved word return and the opening parentheses. The C++ tokens
can be further divided into the following:
(a) Identifiers
(b) Keywords
(c) Constants
(d) Operators
Table 2.1
Escape sequence characters
Execution Meaning Result at execution timeCharacter
\o End of string Null\n End of a line Moves the active position to the initial position
of the next line.\r Carriage Moves the active position to the initial position
return of the next paragraph.\f Form feed Moves the active position to the initial position
of the next logical page.\v Vertical tab Moves the active position to the next vertical
tabulation position.\t Horizontal tab Moves the active position to the next horizontal
tabulation position.\b Backspace Moves the active position to the previous posi-
tion on the current line.
\a Alert Produces an audible alert.\\ Backslash Presents with a backslash \.
Figure 2.1
Tokens and
white space int main(void){
token
white space (carriage return)white space (space)token
Spaces and carriage returns can be used interchangeably.
int
main(void) {
white space (space)
white space (carriage return)token
token
bpbonline all rights reserved
-
8/11/2019 C++Lang chap2
3/12
Part I Basics of C++ 13
2.2.1 Identifiers
Identifiers refer to the names of variables, functions, arrays, classes etc., created by the program-
mer. These are also the names of language objects, which can take many values, one at a time.
Once assigned, their values can be changed during the execution of the program. Values can be
stored in symbolic names (variables) in the computer memory and can be recalled as and when
required.
Usually, variables are named with descriptions that convey the idea of what values they hold.
For example, if a root of a quadratic equation is to be calculated, the variable in which the value of
root is to be stored can be named as root rather than naming it as q or by any other name.
N a m in g a V a ria b le
Variable should be named so as to distinguish one from the other. The following are the rules to
name a variable.
(a) It can consist of any sequence of letters, digits and underscores(_).
(b) No other special characters are allowed.
(c) The first character should be a letter or an underscore. It can be followed by letters, digits
or underscore.
(d) Upper and lower case letters are distinguishable. Though upper case letters are allowed,
usually C++ variables are written in lower case. Thus Num, NUM and num are three dif-
ferent variables.
(e) Reserved / keywords cannot be used as names of identifiers/variables.
V a ria b l e De c la ra tion
Through the declaration statements, C++ compiler interprets the variables in a specific style. A
declaration also causes storage to be reserved for an identifier. All C++ variables should be
declared before their usage. A declaration statement lists the number and type of the variables. A
few declarations are given in Table 2.2.
Table 2.2
Examples of variable declaration
Variable Remarksdeclaration
int i = 0, j = 1; i and j are declared as integers. i and j are initialized with 0 and 1respectively.
float basic_pay; basic_pay is floating point variable.char empl_name; empl_name is a character variable.
double theta; theta is double precision variable.
2.2.2 Keywords / reserved words
At the time of designing a language, some words are reserved to do specific tasks. Such words are
called askeywordsorreservedwords. Table 2.3 gives the a list of C++ language reserved words.
bpbonline all rights reserved
-
8/11/2019 C++Lang chap2
4/12
14 Programming in C++ Part I
Table 2.3
List of C++ reserved words
asm auto breakcase catch charclass const continuedefault delete dodouble else enumextern float forfriend goto if inline int longnew operator privateprotected public registerreturn short signedsizeof static structswitch template thisthrow try typedef union unsigned virtualvoid volatile while
2.2.3 Constants
These are the items which represent values directly and whose values cannot be changed during
the execution of the program. Each constant has a type that is determined by its form and a value.
With respect to form and value, C++ has three types of constants. These are:
(a) Numeric constants
(b) Character constants(c) String constants
Num e ric C onsta n ts
A numeric constant is made up of a sequence of numeric digits with optional presence of a decimal
point (.). These are of two types:
(a) Integer
(b) Floating point
Integer Numeric Constant. A sequence of numeric digits without the decimal point (wholenumber) is called an integer constant. For example, 19 is an integer constant.
Floating Point Numeric Constant. A sequence of numeric digits with the decimal point (i.e. a
fractional number) is called a floating point constant. For example, 15.62 is a floating point con-stant.
C++ allows calculations and arithmetic expressions with decimal, octal and hexadecimal
numbers. A leading 0 and 0x in an integer constant are recognized as octal and hexadecimal con-
stants respectively. For example, 0123 is an octal constant but 0x69f is a hexadecimal constant.
bpbonline all rights reserved
-
8/11/2019 C++Lang chap2
5/12
Part I Basics of C++ 15
C ha ra c te r C onsta n t
Any single character given withinsinglequotes is called a character constant. Escape sequences
are character constants though they are represented by two characters. For example, \o and Aare character constants.
String C on sta nt
Strings are the form of data used in programming languages for storing and manipulating text,
such as words, names and sentences. In C++, string is an array of characters. Thus "Greetings" is a
string constant. Thus a string constant is a sequence of zero or more characters enclosed within
doublequotes.
2.2.4 OperatorsAn operator in C++ specifies an operation to be performed that yields a value. An operand is an
entity on which an operator acts. C++ language operators are classified into four types:
(a) Arithmetic
(b) Relational
(c) Logical/boolean
(d) Assignment
These can be further categorized as follows:
(i) Unary operator: requires one operand
(ii) Binary operator: requires two operands
(iii) Ternary operator: requires three operandsArithm e tic O pe ra tors
An operator that performs an arithmetic (numeric) operation:+, ,*,/,or%. Using theseoperators and combining them with constants and variables, you can create an arithmetic expres-
sion.
Unary Operator. An operator that takes only one operand. For example, unary minus (as in2.5).
Binary Operator In this case two operands are needed to write an arithmetic expression. In C++there is no operator to find exponentiation of a value. The separate function needs to be written forthis purpose. Table 2.4 gives the binary arithmetic operators.
Table 2.4
List of binary operators
Binary operator Meaning
+ PlusMinus
* Multiplication/ Division% Modulus operator for remainder, used with integer
numbers
bpbonline all rights reserved
-
8/11/2019 C++Lang chap2
6/12
16 Programming in C++ Part I
Examples of binary arithmetic are:
basic_pay + da - pf*6.0/100
u*t + 0.5*a*t*t
Ternary Operator This is a special feature of C++ language. As the name suggests, this caseneeds three operands. For example:
Test operand ? operand1:operand2;
If the test operand results with true, the value of operand1 is taken otherwise the value of oper-
and2 is taken for further processing. Another example is:
big = a > b ? a : b;
In the above statement, if a > b thenais assigned to big otherwisebis assigned to big.
Re la tiona l O pe ra tors
The relational operators are used to test the relation between two values. All C++ relational oper-
ators are binary operators and hence require two operands.
A relational expression is made up of two arithmetic expressions connected by a relational
operator. It returns zero when the relation isfalseand a nonzero when it is true. The operators are
given in Table 2.5.
Table 2.5 List of Relational operators
Relational operators Meaning
< Less than Greater than
>= Greater than or Equal!= Not equal
For example,
a > big
returns a value zero (false), whenais not greater thanbig, otherwise, a nonzero (true) is returned.
Log i ca l/ Boo l ea n O pe ra to rs
Table 2.6
List of logical/boolean operators
C++ Symbol Logical Type of operatoroperator
! NOT Unary operator&& AND Binary operator|| OR Binary operator
bpbonline all rights reserved
-
8/11/2019 C++Lang chap2
7/12
Part I Basics of C++ 17
Logical operators combine the results of one or more expressions and it is called logical
expression. After testing the conditions, they return logical status (true or false) as net result. The
logical operators are unary or binary operators. The operands may be constants, variables or
expressions. Table 2.6 gives a list of logical operators.
Assignm e nt O pe ra to r
Assignment operator (=) stores the value of the expression on the right hand side of the equal sign
in the object represented by the left hand side of the equal sign. Assume that the following decla-
rations are given:
int m = 3, n = 4;float x = 2.5, y = 1.0;
Table 2.7 explains expressions using assignment operators.
Table 2.7
Using assignment operator
Expression Equivalent Expression Result
m = = n + x y m = (m + ((n + x) y)) 8m /= x * n + y m = (m / ((x * n) + y)) 0
x += y -= m x = (x + (y = (y - m))) 0.5n %= y + m n = (n % ( y + m)) 0
2.3 STRUCTURE OF C++ PROGRAM
All C++ programs are divided into units called "functions". The program also contains the list of
library files included for utilizing the functions. For example, the library file is usedin the program shown in Figure 2.2 where the definition of the keywordscoutandcinis given.
The C++ program given in Figure 2.2 has the functionmainfollowed by parentheses. Just after
the name of the functionmain, the braces signal the beginning and end of the body of the function.
The opening brace ( { ) indicates a block of code that forms a distinct unit which is about to begin.
The closing brace ( } ) terminates the block of code.
Figure 2.2
A sample pro- #includegram in C++ void main ()
{ int x, y, z;
cout > x;cout y;z = x + y;cout
-
8/11/2019 C++Lang chap2
8/12
18 Programming in C++ Part I
The function heading tells us what kind of return value, if any, the function produces and
what sort of information it expects to be passed to it by arguments. The function body consists of a
series of C++ statements enclosed in paired braces { }.
Ex a m p le 1
When you read the program shown in Figure 2.2, you would notice that the The fist line of the
program consists of a header file known as iostream.hso that you can use the functions coutand
cindefined in this file. The functioncoutdisplays the value of a variable on the monitor and the
functioncinallows you to input the value from the keyboard. Each line of the program ends with a
semicolon(;). Every complete statement in C++ must be terminated with a semicolon. The pro-
gram asks you to enter two integer numbers and displays the sum of the two numbers.
Another aspect of programs in C++ is that they are written in lower case. The C++ languagedistinguishes between upper and lower case letters.
C++ has the following types of statements:
(a) Declaration statement
(b) Assignment statement
(c) Function call statement
(d) Object message statement
(e) Return statement
De c la ra tion sta te m e nt
The declaration statement announces the name of a variable and establishes the type of data it can
hold.
Assignm e nt statem e nt
An assignment statement gives a value to a variable.
Func tion c a ll sta te m e nt
A function call statement passes program control to the called function. When the function
finishes, control returns to the statement in the calling function immediately following the function
call.
Re turn sta te m e nt
A return statement is the mechanism by which a function returns a value to its calling function.
2.3.1 Include Files or Reprocessor DirectivesC++ has its own set of input/output library syntax which is very easy to use. This is defined in a
header file called iostream.h. These header files contain all the information a user requires in
order to make use of the libraries. In order to access a variable or function defined within the
standard libraries, we must include the associated header file into our program. It must be included
in our program before main. The syntax for including a library file is the hash sign (#) followed
by the word include, followed by the name of the appropriate header file in pointed brackets ()
as shown below:
bpbonline all rights reserved
-
8/11/2019 C++Lang chap2
9/12
Part I Basics of C++ 19
#include
This statement allows us to access a large object oriented library of I/O functions such as cout,
cin etc. #include is referred to as a preprocessor directive. It causes the contents of iostream.h to
be read into the program.
A program source file consists of two parts a file name and a file suffix. The file suffix
serves to identify the contents of the file. This suffix will vary from C++ package to package. In
Borland C++, the suffix used is .cpp.
The #include directive reads in the contents of the named file. It takes one of two forms:
#include #include "my_io.h"
If the file name is enclosed within angle brackets ("") the file is presumed to be a pre-defined, or standard, header file. The search to find it will examine a pre-defined set of locations.
If the file name is enclosed within a pair of quotation marks (" "), the file is presumed to be a
user-supplied header file. The search to find it begins in the current directory. If it is not found,
then the pre-defined set of locations is examined.
2.3.2 Declaration of an Object
A class in C++ is a user-defined specification for a data type. This specification details how infor-
mation is to be
represented and also the operations that can be performed with the data. An object is an entity
created according to a class prescription, just as a simple variable is an entity created according to
a data type description. C++ provides two pre-defined objects (cinand cout) for handling inputand output.
2.3.3 Main Function
C++ program consists of one or more modules called functions. Programs begin executing at the
beginning of the function calledmain(), so you should always have a function by this name. Pro-
gram execution continues by sequentially executing the statements withinmain(). A program ter-
minates normally following execution of the last statement of main().
2.4 COUT
To output data onto the screen, we use the word cout followed by the insertion operator, which
is two smaller than symbols:
-
8/11/2019 C++Lang chap2
10/12
20 Programming in C++ Part I
cout
-
8/11/2019 C++Lang chap2
11/12
Part I Basics of C++ 21
enter a number 7enter another number 8
2.6 USE OF I/O OPERATORS (>)
The output operator (">") is used to read a value from standard input such as the
keyboard. Blank space, tabs and newlines are referred to aswhite spacein C++. The statement
cin >> v1 >> v2;
correctly reads in the two values because the input operator (">>") discards all white space that it
encounters.
Declarations ofcinandcoutare contained within the header fileiostream.h. If you forget to
include this file, then each reference to eithercinorcoutwill be flagged as a type error by the C++
compiler.
2.8 ERROR MESSAGE
When the compiler detects an error, the computer will display an error message, which indicatesthat you have made a mistake and what the cause of the error might be. Two basic categories of
error messages will occur. These are:
(a) Syntax error or compilation error messages
(b) Run-time error messages
bpbonline all rights reserved
-
8/11/2019 C++Lang chap2
12/12
22 Programming in C++ Part I
2.8.1 Syntax Error or Compilation Error Messages
These error and messages are detected and displayed by the compiler as it attempts to translate the
program. If a statement has a syntax error, it cannot be translated and the program will not be
executed.
Some examples of the syntax error messages are:
(a) Missing semicolon at the end of the variable declaration
(b) Undeclared variable name
(c) Unexpected end of the file
As you will write and execute the programs, you will get more familiar with this type of error
messages.
2.8.2 Run-time Error Messages
Run-time errors are detected by the computer and are displayed during the execution of a program.
A run-time error occurs when the program directs the computer to perform an illegal operation,
such as dividing a number by zero. When a run-time error occurs, the computer stops executing
the program and prints a message which helps detect the error in the program. Such a message is
known as Run-time error message and it helps in diagnosing the mistake in the program at the time
of execution.
TEST PAPER
Time: 3 Hrs
Max Marks: 100
Answer the following questions.
1. Indicate which of the following is true about C++ tokens.
(a) Each token should not be separated from the other by a space or tab or carriage
return.
(b) Identifiers is a subdivision of a token.
2. Define the term constant as used in C++. What are the three different classifications of
constant. Explain each one of them.
3. Differentiate between the terms operand and the operator. State different types of opera-
tors used in C++ and give one example of each.
4. Explain with an example, the structure of a C++ program. What is the role played bycout
andcinin a program.
5. Differentiate between the runtime and syntax error with the help of an example.
6. Write a short note on the following:
(a) Keywords/Reserve words used in C++ language
(b) Cascading of I/O operators
bpbonline all rights reserved