0% found this document useful (0 votes)
16 views18 pages

CH03LOOPETC

Uploaded by

renukathakre80
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views18 pages

CH03LOOPETC

Uploaded by

renukathakre80
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

BASICS OF C++

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 and Constants

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

INTEGER REAL SINGLE STRING


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++

The mantissa is either a real number expressed in decimal notation or an integer.


The exponent is an integer number with an optional plus or minus sign. The letter e separating the mantissa
and the exponent can be written in uppercase or lowercase letter.
Example: 0.65e4 12-e2 1.5e+5 3.18E3 -1.2E-1
Some of the invalid constants are
Example Reason
2.5e10.2 In exponent decimal point is not allowed
10,000.2e2 Comma is not allowed
123 .e10 Space not allowed
[email protected] Special symbol not allowed

SINGLE CHARACTER CONSTANT


A single character constant may be a single letter or single digit or single special symbol
enclosed in single quotation. All the character constants must have unique values in the ASCII
character set. For example the ASCII value of the character constant ‘a’ is 97.
Valid examples of single character constants are ‘a’ ‘1’ ‘@’ ‘&’
Invalid examples of single character constant
Example Reason
‘18’ Maximum length is one
a Must be in single quote
“s” Must be enclosed in single quote

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

BACKSLASH CHARACTER CONSTANT (NON PRINTABLE CHARACTERS OR ESCAPE SEQUENCES)


C allows using some special backslash character constants also called as escape sequences or non-
printable characters. For example, the symbol ‘\n’ stands for newline character. The escape sequence
always starts with backslash character and followed by one or more character. Following are the
some of the backslash characters.
Constant Meaning
‘\a’ Audible alert (bell)
‘\b’ Back space
‘\f’ Form feed
‘\n’ New line
‘\r’ Carriage return
‘\t’ Horizontal tab
‘\v’ Vertical tab

5|Page
BASICS OF C++

‘\’’ Single quote


‘\’’’ Double quote
‘\?’ Question mark
‘\\’ Backslash
‘\0’ null

BASIC DATA TYPES

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.

BUILT-IN DATA TYPES (PRIMARY DATA TYPES)


All C compilers support five fundamental data types, namely integer(int), character(char), floating
point(float), double-precision floating point(double) and void. They are also called as primitive data
types. The range and the memory requirement for each data type is given in below table.
Data type Range of values Memory required
char -128 to 127 1 byte
int -32768 to 32767 2 bytes
float 3.4e-38 to 3.4e38 4 bytes
double 1.7e-308 to 1.7e308 8 bytes

6|Page
BASICS OF C++

char DATA TYPE


The char is a keyword and it is used to store a single character in memory. Character usually requires
8bits (1 byte)of memory. The range of char is -128 to 127. All the characters have unique values in
the ASCII character set. For example, the ASCII value for character ‘a’ is 97. An example of declaration
of character type of variable is char a;
this example declares the variable a as character where we can store single character in it.
int DATA TYPE
The int is keyword and is used to specify the integer type of data i.e. sometimes known as
whole number means the number without decimal point. Integer takes two bytes in memory. The
valid range of int is -32768 to 32767. It means we cannot store number lesser than -32768 and
greater than 32767 when data type is int. An example to declare int type of variable is int x,y;
where x and y are the int type of variables.
float DATA TYPE
The float is keyword and is used to specify the floating type of data i.e. the number with
decimal point. For example 3.14,15.23 are the floating point numbers. Sometimes it is also called as
real numbers. It occupies 4 bytes in memory with 6 digits of precision. The range of float data type is
3.4e-38 to 3.4e38. An example to declare float type of variable is float no1,no2;
where no1 and no2 are the float type of variable where we can store floating point numbers and will
occupy 4 bytes each.
double DATA TYPE
The floating point number can also be specified with another data type double. You can use
the keyword double for it. The double occupies 8 bytes with 14 digits precision. The range of double
data type is 1.7e-308 to 1.7e308. An example to declare double type of variable is double sal;
Where sal is the double type of variable which occupies 8 bytes memory. The main difference
between float and double is float is up to 6 digits of precision and double is up to 8 digits of precision.

DATA TYPE MODIFIERS


Let us consider an example of a program, which will accept an age from the user to do some
processing. Because the age is represented in numbers, so we will have to use the integer data type
int. We all know that even under exceptional case an age of a person cannot exceed more than 150.
Now, that we are using an integer data type it occupies 2 Bytes of memory, which would not be
required to represent the value 150. Instead the value 150 could easily be saved in an integer of 1
Byte in size, but the default size of an integer is 2 Bytes. So we have a problem here.
To override the default nature of a data type, C has provided us with data type modifiers as follows:
signed
By default all data types are declared as signed. Signed means that the data type is capable of storing
negative values.
unsigned
To modify a data type behavior so that it can only store positive values, we require to use the data
type unsigned.For example, if we were to declare a variable age, we know that an age cannot be
represented by negative values and hence, we can modify the default behavior of the int data type as
follows:
unsigned int age;

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.

User-Defined Data Types


Structure & Union
A structure contains an ordered group of data objects. Unlike the elements of an array, the data
objects within a structure can have varied data types. Each data object in a structure is a member or
field. A union is an object similar to a structure except that all of its members start at the same
location in memory. A union variable can represent the value of only one of its members at a time.

In C++, structures and unions are the same as classes except that their members and inheritance are
public by default.

ENUMERATED DATA TYPE


An enumerated data type is another user-defined type. An enumeration is a data type
consisting of a set of named values that represent integer constants, known as enumeration
constants. An enumeration also referred to as an enumerated type because you must list each of the
values in creating a name for each of them. The enum keyword automatically enumerates a list
of words by assigning them values 0.1,2, and so on.
The syntax of an enum statement is similar to that of the struct staement. Examples:
enum shape{circle, square, triangle);
enum co1our{red, blue, green,yellow);
Now you can declare the variable of type shape and colour type

8|Page
BASICS OF C++

shape ellipse; // ellipse is of type shape


colour background; // background is of type colour

DERIVED DATA TYPES


An array is a series of elements of the same type placed in contiguous memory locations. It means
that, for example, we can store 5 values of type int in an array without having to declare 5 different
variables, each one with a different identifier. Instead of that, using an array we can store 5 different
values of the same type.
For example, an array to contain 5 integer values of type int called sample could be represented like
this:

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++

Pointers are declared and initialized as in C. Examples:

int *ip; // int pointer


ip = &x; // address of x assigned to ip
*ip = 10; // 10 assigned to x through indirection
C++ adds the concept of constant pointer and pointer to a constant.

char * const ptrl = "GOOD"; // constant pointer

We cannot modify the address that ptrl is initialized to.

int const * ptr2 =&m; // pointer to a constant

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++

DYNAMIC INITIALIZATION OF VARIABLES

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:

SCOPE RESOLUTION OPERATOR

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;
}

The output of the program would be:

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++

MEMBER DEREFERENCING OPERATORS

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.

These operators are further discussed in the next chapter.

Memory Management Operators

C uses malloc() and calloc() functions to allocate memory dynamically at run


time. Similarly, it uses the function freed to free dynamically allocated
memory. Although C++ supports these functions, it also defines two unary
operators new and delete that perform the task of allocating and freeing the
memory in a better and easier way. Since these operators manipulate memory on the
free store, they are also known as free store operators.

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:

pointer-variable = new data-type[size];


Here, size specifies the number of elements in the array. For example, the statement
int *p=new int[10];

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;

will delete the entire array pointed to by 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:

Expressions and Their Types


An expression is a combination of operators, constants and variables arranged
as per the rules of the language. It may also include function calls which return
values. An expression may consist of one or more operands, and zero or
more operators to produce a value. Expressions may be of the following seven
types:
• Constant expressions
• Integral expressions
• Float expressions
• Pointer expressions
• Relational expressions
• Logical expressions
• Bitwise expressions
An expression may also use combinations of the above expressions. Such
expressions are known as compound expressions.

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++

where m and n are integer variables.

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:

a>b && x<10


x<10 || y>=5
Bitwise Expressions
Bitwise Expressions are used to manipulate data at bit level. They are basically used for
testing or shifting bits. Examples:

x« 3 // Shift three bit position to left

16 | P a g e
BASICS OF C++

y»1 // Shift one bit position to right


Shift operators are often used for multiplication and division by powers of two.

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

The switch statement


This is a multiple-branching statement where, based on a condition, the
control is transferred to one of the many possible points. This is
implemented as follows:

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;

The while statement


This is also a loop structure, but is an entry-controlled one. The syntax is as
follows:

while(cond1t1on is true)
{
actionl;
)
Action2;

The for statement


The for is an entry-controlled loop and is used when an action is to be
repeated for a pre-determined number of times. The syntax is as following:

19 | P a g e
BASICS OF C++

for(initial value; test; increment)

{
Action1;
}
action2;

20 | P a g e

You might also like