CH03LOOPETC
CH03LOOPETC
Tokens
The smallest individual units in a program are known as tokens. C++ has the following tokens:
• Keywords
• Identifiers
• Constants
• Strings
• Operators
KEYWORDS
Keywords are the reserved words that have special meaning to the compiler i.e. keywords are the
words whose meaning is already been explained to C++ compiler. Keywords serves basis building
block for the program statements. They are explicitly reserved identifiers and cannot be
used as names for the program variables or other user-defined program
elements.
C++ Keywords
Identifiers refer to the names of variables, functions, arrays, classes, etc. created by the
programmer. They are the fundamental requirement of any language. Each language has its
own rules for naming these identifiers. The following rules are common to both C and C++:
• Only alphabetic characters, digits and underscores are permitted.
• The name cannot start with a digit.
• Uppercase and lowercase letters are distinct.
• A declared keyword cannot be used as a variable name.
A major difference between C and C++ is the limit on the length of a name. While ANSI C recognizes
only the first 32 characters in a name, ANSI C++ places no limit on its length.
3|Page
BASICS OF C++
CONSTANTS
CONSTANTS
NUMERIC CHARACTER
Constant means fixed values which do not change during the execution of a program. Several types
of constant are shown in the above figure.
INTEGER CONSTANTS
An integer constant refers to a sequence of digits. Rules for constructing integer constants are
1. An integer constant must have at least one digit.
2. Decimal point is not allowed in integer constant.
3. It would be either positive or negative, if sign omitted then number is considered as positive.
4. Comma and blank spaces not allowed, also you cannot use special symbols also.
5. The range of integer types depends on data type.
There are three types of integer constants
1. Decimal integer constant 2. Octal integer constant 3. Hexadecimal integer constant
DECIMAL INTEGER CONSTANT
Decimal integer consist of a set of digits 0 through 9, sign may be + or –(Minus). Embedded spaces,
commas, and non-digit characters are not permitted between digits.
Legal examples Illegal numbers
123 15 750
-321 20,000
+78 $1000
0 1.000
OCTAL INTEGER CONSTANT
An octal integer constant consists of any combination of digits from the set 0 through 7, with a
leading 0. Some examples of octal integer are 037 0 0435 0551
HEXADECIMAL INTEGER CONSTANT
A sequence of digits preceded by 0x and 0X is considered as hexadecimal integer. They may include
alphabets A through F or a through f. The letter A through F represent numbers 10 through 15.
Following are examples of valid hex integers 0X2 0x9E 0Xbd 0A
REAL CONSTANTS
Since integer numbers are not sufficient to represent the entities which vary continuously like
distances, heights, temperatures, prices and so on. These numbers are represented by containing
fractional parts line 17.578 such numbers are called real constants. These numbers are the whole
numbers followed by decimal point and factional part. It is possible to omit digits before the decimal
point, or digits after the decimal point. That is, 215 0.95 -.75 +.5
A real number may also be expressed in exponential notation. For example the value 215.65 may be
written as 2.1565e2 in exponential notation. E2 means multiply by 10 2. The general form is
4 mantissa
| P a g e e exponent
BASICS OF C++
STRING CONSTANTS
A string constant is a sequence of characters enclosed in double quotations. The characters
may be letters, numbers, special characters and blank space.
Valid examples are ” hello!” “all is well” “1979” “good! 2times”
Invalid examples area
Example Reason
“enter radius Right hand double quote is missing
‘area’ Single quote is not allowed
Weight Must be enclosed in double quote
5|Page
BASICS OF C++
C++ language is rich in its data types. Data type tells which type of data will be stored in variable and
how much memory it will occupy. The variety of data types available in C++ allows selecting the
appropriate data type according to need of application.
6|Page
BASICS OF C++
7|Page
BASICS OF C++
This declaration allows the age variable to store only positive values. An immediate effect is that the
range changes from (-32768 to 32767) to (0 to 65536)
long
Many times in our programs we would want to store values beyond the storage capacity of the basic
data types. In such cases we use the data type modifier long. This doubles the storage capacity of the
data type being used. E.g. long int salary will make the storage capacity of variable salary to 4 bytes.
short
If long data type modifier doubles the size, short on the other hand reduces the size of the data type
to half.
In C++, structures and unions are the same as classes except that their members and inheritance are
public by default.
8|Page
BASICS OF C++
Sample
The application of arrays in C++ is similar to that in C. The only exception is the way
character arrays are initialized. When initializing a character array in C, the compiler
will allow us to declare the array size as the exact length of the sting constant. For
instance,
char string [3] =”xyz”;
is valid in ANSI C. It assumes that the programmer intends to leave out the null character
\0 in the definition. But in C++, the size should be one larger than the number of
characters in the sting.
char string[4] = "xyz";
FUNCTIONS
Functions continued to be building block of C++ programs. C++ has added many new features to
functions to make them more reliable and flexible. In C++ function can be overloaded to make it
perform different tasks depending on the arguments passed to it. Most of these modifications are
aimed at meeting the requirements of object-oriented facilities.
In special chapter of functions, details are discussed.
POINTERS
Pointer is a variable which store the address of another variable i.e. the pointer is a variable that
point to another variable. This means that a pointer holds the memory address of another variable.
Feature of pointer
Execution time with pointer is fast because data is manipulated with the address.
Pointer reduces the length and complexity of program.
Pointers are more efficient in handling data.
Pointer enable us to access a variable that is defined outside the function.
Pointer provides dynamically allocation.
Pointer provides a convenient way to represent multidimensional array.
Pointers are used with data structure.
9|Page
BASICS OF C++
ptr2 is declared as pointer to a constant. It can point to any variable of correct type,
but the contents of what it points to cannot be changed.
Reference Variables
C++ introduces a new kind of variable known as reference variable. A reference variable provides
alternate name for previously defined variable. For example, if we make the variable sum a reference
to the variable total, then sum and total can be used interchangeably to represent that variable.
Syntax to declare reference variable is given below:
data-type &reference-name=variable-name;
Example:
float total=100;
float &sum=total;
here total is a float type variable that has already been declared; sum is the alternative name
declared to represent the variable total. Both the variables refer to the same data object in the
memory. Now if you want to print the value of both i.e. of total and sum, the result will be same
i.e.100.
Also if you make changes in any of two, same will be reflected for other because the memory
location for both is same but with two names.
A reference variable must be initialized at the time of declaration. This establishes the
correspondence between the reference and the data object with it names.
Declaration of Variables
C requires all the variables to be defined at the beginning of a scope. C++ allows the
declaration of a variable anywhere in the scope. This means that a variable can be
declared right at the place of its first use. This makes the program much easier to
write and reduces the errors that may be caused by having to scan back and
forth. It also makes the program easier to understand because the variables are
declared in the context of their use.
10 | P a g e
BASICS OF C++
C++ permits initialization of the variables at run time referred to as dynamic initialization. In C++, a
variable can be initialized at run time using expressions at the place of declaration. For example
float average;
average=sum/i;
can be combined into a single statement
float average=sum/i;
Dynamic initialization is extensively used in object-oriented programming.
OPERATORS IN C++
All C operators are valid in C++ also. C++ itself introduces some new operators. We’ve seen already
two of them i.e. insertion operator <<, and the extraction operator>>. Other new operators are:
Blocks and scopes can be used in constructing programs. We know that the same variable
name can be used to have different meanings in different blocks. The scope of the variable
extends from the point of its declaration till the end of the block containing the declaration. A
variable declared inside a block is said to be local to that block.
The global version of a variable cannot be accessed from within the inner block. C++ resolves
this problem by introducing a new operator :: called the scope resolution operator.
Syntax: ::variable-name;
This operator allows access to the global version of a variable. Following program
demonstrates the operator.
11 | P a g e
BASICS OF C++
#include<iostream.h>
int m=10; //global m
int main()
{
int m=20; //m declared, local to main
{
int k=m;
int m=30; //m declared again local to inner block
cout<<”We are in inner block\n”;
cout<<”k=”<<k<<”\n”;
cout<<”m=”<<m<<”\n”;
cout<<”::m=”<<::m<<”\n”;
}
Cout<<”\nWe are in outer block\n”;
Cout<<”m=”<<m<<”\n”;
Cout<<”::m=”<<::m<<”\n”;
return 0;
}
A major application of the scope resolution operator is in the classes to identify the class to which
a member function belongs.
12 | P a g e
BASICS OF C++
C++ permits us to define a class containing various types of data and functions as
members. C++ also permits us to access the class members through pointers.
NEW OPERATOR
An object can be created by using new. A data object created inside a block
with new, will remain in existence until it is explicitly destroyed by using delete.
Thus, the lifetime of an object is directly under our control and is unrelated to the
block structure of the program.
The new operator can be used to create objects of any type. It takes the following
general form:
pointer-variable=new datatype;
Pointer-variable is a pointer of type data-type. The new operator allocates sufficient
memory to hold a data object of type data type and returns the address of the
object. The data type may be any valid data type. The pointer-variable holds the
address of the memory space allocated. Examples:
p = new int;
q = new float;
where p is a pointer of type int and q is a pointer of type float. Here, p and q must
have already been declared as pointers of appropriate types. new can be used to
create a memory space for any data type including user-denied types such as arrays,
structures and classes. The general form for a one-dimensional array is:
13 | P a g e
BASICS OF C++
creates a memory- space for an array of 10 integers. p[0] will refer to the first element,
p[1] to the second element, and so on.
The new operator offers the following advantages over the function malloc().
1.It automatically computes the size of the data object. We need not use the operator
sizeof.
2.It automatically returns the correct pointer type, so that there is no need to use a
type cast.
3. It is possible to initialize the object while creating the memory space.
4. Like any other operator, new and delete can be overloaded.
DELETE Operator
Delete operator is used to destroy the object created by new. When a data object is
no longer needed, it is destroyed to release the memory space for reuse. The general
form of its use is:
delete pointer-variable;
The pointer-variable is the pointer that points to a data object created with new. Examples:
delete p;
delete q;
If we want to free a dynamically allocated array, we must use the following form of
delete:
delete [size] pointer-variable;
The size specifies the number of elements in the array to be freed. The problem with this
form is that the programmer should remember the size of the array. But in new versions
of C++, no need to remember the size. You can do it like given below:
delete [ ]p;
Manipulators
Manipulators are operators that are used to format the data display. The most
commonly used manipulators are endl and setw.
endl
The endl manipulator, when used in an output statement, causes a linefeed to be inserted. It
has the same effect as using the newline character "\n". For example:
cout << m << endl << n << endl <<p;
would cause three lines of output, one for each variable. If we assume the values
of the variables as 2597, 14. and 175 respectively, the output will appear as follows:
14 | P a g e
BASICS OF C++
setw
If the output is number then it should be printed right justified. The setw manipulator does
this job. It is used as follows:
cout « setw(5) « sum « endl;
The manipulator setw (5) specifies a field width 5 for printing the value of the variable
sum as shown below:
Constant Expressions
Constant Expressions consist of only constant values. Examples:
Integral Expressions
Integral Expressions are those which produce integer results after implementing
all the automatic and explicit type conversions. Examples:
15 | P a g e
BASICS OF C++
Float Expressions
Float Expressions are those which, after all conversions, Examples:
X+Y
X+Y/10
5+float(10)
10.75
Where X & Y are floating-point variables.
Pointer Expressions
Pointer Expressions produce address values. Examples:
&m
ptr
ptr+1
where m is variable and p is pointer variables.
Relational Expressions
Relational Expressions gives results of type Boolean which takes a value true or false. Examples:
X<=Y
M+N==P-Q
When arithmetic expressions are used on either side of a relational operator, they will
be evaluated first and then the results compared. Relational expressions are
also known as Boolean expressions.
Logical Expressions
Logical Expressions combine two or more relational expressions and produces
Boolean type results. Examples:
16 | P a g e
BASICS OF C++
Control Structures
One method of achieving the objective of an accurate, error-resistant and
maintainable code is to use one or any combination of the following three
control structures:
1. Sequence structure (straight line)
2. Selection structure (branching)
3. Loop structure (iteration or repetition)
Following figure shows how these structures are implemented using one-entry,
one-exit concept, a popular approach used in modular programming.
It is important to understand that all program processing can be coded by using only
these three logic structures. The approach of using one or more of these basic control
constructs in programming is known as structured programming.
C++ also supports all the three basic control structures, and implements them using
various control statements as shown in Figure given below.
17 | P a g e
BASICS OF C++
The if statement
The if statement is implemented in two forms:
• Simple if statement
• if...else statement
switch(expression)
{
Case l:
18 | P a g e
BASICS OF C++
(
Action l;
}
Case2:
{
action2;
)
case3:
{
action3;
)
default:
{
action4;
}
)
action5;
DO-WHILE STATEMENT
The do-while is an exit controlled loop based on a condition. This control is
transferred back to a particular point in the program. The syntax is as follows
do
{
actionl;
)
while(condition is true);
act1on2;
while(cond1t1on is true)
{
actionl;
)
Action2;
19 | P a g e
BASICS OF C++
{
Action1;
}
action2;
20 | P a g e