0% found this document useful (0 votes)
30 views

Components of A C

The document discusses the components of a C++ program including objects, classes, methods, and instance variables. It then summarizes the structure of a simple C++ "Hello World" program including main functions, headers, namespaces, comments, and output statements. Finally, it describes the basic elements of C++ such as tokens, keywords, identifiers, constants/literals including integer, floating-point, boolean, character, and string literals.

Uploaded by

arpanabharani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Components of A C

The document discusses the components of a C++ program including objects, classes, methods, and instance variables. It then summarizes the structure of a simple C++ "Hello World" program including main functions, headers, namespaces, comments, and output statements. Finally, it describes the basic elements of C++ such as tokens, keywords, identifiers, constants/literals including integer, floating-point, boolean, character, and string literals.

Uploaded by

arpanabharani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

2.

1 Components of a C++ program


The various essential components of a C++ program are as explained below:

1. Object − The object in C++ consists of states and behaviors . An object is an instance of
the class Example: A car has states - color, name, brand as well as behaviors - mileage, speed. An
object is an instance of a class.
2. Class − Classes are the language element in C++ most important to the support object-
oriented programming (OOP). A class defines the properties and capacities of an object. It
can be defined as a template or blueprint that describes the behaviors or states that object of its type
support.

3. Methods − A method defines the behavior of a class. There can be many methods in a
class. In methods the logics are written, data is manipulated and all the actions in the
code are executed.
4. Instance Variables − : There is a set of instant variables associated with the objects.
An object's state is created by the values assigned to these instance variables.

2.1.1 C++ Program Structure


Consider a simple code that print the words Hello World.

#include <iostream>
using namespace std;

// main() is where program execution begins.


int main()
{
cout << "Hello World"; // prints Hello World
return 0;
}

The various parts of the above program are−

 Header, which contain information that is either necessary or useful to your program.
For this program, the header <iostream> is needed.
 The line using namespace std; tells the compiler to use the std namespace.
Namespaces is a recent addition to C++.
 The next line '// main() is where program execution begins.' is a single-line
comment available in C++. Single-line comments begin with // and stop at the end of
the line.
 The line int main() is the main function where program execution begins.
 The next line cout << "Hello World."; causes the message "Hello World" to be
displayed on the screen.
 The next line return 0; terminates main( )function and causes it to return the value 0
to the calling process.
2.1.2 Compile and Execute C++ Program
Follow the steps to save, compile and run the program −

 Open a text editor and add the code as above.


 Save the file as: hello.cpp
 Open a command prompt and go to the directory where you saved the file.
 Type 'g++ hello.cpp' and press enter to compile your code. If there are no errors in
your code the command prompt will take you to the next line and would generate a.out
executable file.
 Now, type 'a.out' to run your program.
 You will be able to see ' Hello World ' printed on the window.

2.2 Basic Elements of C++


2.2.1 Token
The smallest individual unit of a program written in any language is called a token. C++
tokens are divided into special symbols, word symbols or keywords, and identifiers.
Special Symbols
Special symbols include mathematical symbols and punctuation marks. Blank is also a
special symbol. Some tokens made up of two characters (with no blank)--still considered
as single symbol.
Examples:
+ ?
- ,
* <=
/ !=
. ==
; >=
Keywords and Reserved words
Keywords are predefined identifiers, that are used in the syntax and can be used as
identifiers again.
Reserved words are the words in a programming language which has a fixed meaning and
cannot be redefined by the programmer. They cannot be used as identifiers (variables,
functions etc).
All reserved words and keywords are in lowercase letters. But this terminology is not
standard. For example, In some books it was mentioned that Reserved words are also
called as Reserved Keywords and some authors will use keyword in the same sense that
we have used Reserved word.

In fact all keywords are subset of Reserve words. Keywords can be redefined while
reserved words cannot be redefined and used.
For example :
Example 1:
#include<iostream>
using namespace std;
int main() // here main is the keyword
{
int main; // it can be redefined
main = 1;
cout<< main;
return 0;
}
Here main is the keyword. So it can be redefined and used as an identifier.
Output :
1
Example 2:
#include <iostream>
using namespace std;
int main()
{
int auto;
auto = 1;
cout<< auto;
return 0;
}
Here auto is a reserved word. It cannot be redefined. So it gives an error.

2.2.1 C++ Reserved Words

The reserved words of C++ may be conveniently placed into several groups. In the first group,
we put those that were also present in the C programming language and have been carried
over into C++. There are 32 such reserved words:
auto const double float int short struct unsigned
break continue else for long signed switch void
case default enum goto register sizeof typedef volatile
char do extern if return static union while

There are another 30 reserved words that were not in C, are therefore new to C++:
asm dynamic_cast namespace reinterpret_cast try
bool explicit new static_cast typeid
catch false operator template typename
class friend private this using
const_cast inline public throw virtual
delete mutable protected true wchar_t

The following 11 C++ reserved words are not essential when the standard ASCII character set
is being used, but they have been added to provide more readable alternatives for some of the
C++ operators, and also to facilitate programming with character sets that lack characters
needed by C++.
and bitand compl not_eq or_eq xor_eq
and_eq bitor not or xor
Identifiers

In C++, an identifier is a name assigned to a function, variable, or any other user-defined item. Identifiers can
be from one to several characters long. Variable names can start with any letter of the alphabet or an
underscore. Next comes a letter, a digit, or an underscore. The underscore can be used to enhance the
readability of a variable name, as in line_count. Uppercase and lowercase are seen as different; that is, to C++,
myvar and MyVar are separate names. There is one important identifier restriction: you cannot use any of the
C++ keywords as identifier names. In addition, predefined identifiers such as cout are also off limits.

Here are some examples of valid identifiers:

Remember, you cannot start an identifier with a digit. Thus, 98OK is invalid. Good programming practice
dictates that you use identifier names that reflect the meaning or usage of the items being named.

Some Predefined Identifiers

Here is a short list of some predefined identifiers:

cin endl INT_MIN iomanip main npos std


cout include INT_MAX iostream MAX_RAND NULL string

2.3 Constants/Literals
Constants or Literals are fixed values which never change their value throughout the
execution of the program. Constants are treated just like regular variables except that their
values cannot be modified after their definition.

Constants can be of any of the basic data types and can be divided into Integer Numerals,
Floating-Point Numerals, Characters, Strings and Boolean Values.

2.3.1 Types of literals


Integer Literals

An integer constant can be a decimal, octal, or hexadecimal constant. A prefix specifies the
base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and
long, respectively. The suffix can be uppercase or lowercase and can be in any order.

Here are some examples of integer literals −

313 // Legal
316u // Legal
0xFeeL // Legal
058 // Illegal: 8 is not an octal digit
042UU // Illegal: cannot repeat a suffix

Following are other examples of various types of Integer literals −

85 // decimal
0213 // octal
0x4b // hexadecimal
30 // int
30u // unsigned int
30l // long
30ul // unsigned long

Floating-point Literals

A floating-point literal consists of an integer part, a decimal point, a fractional part, and an
exponent part. The floating point literals can be represented either in decimal form or
exponential form.

While representing using decimal form, you must include the decimal point, the exponent, or
both and while representing using exponential form, you must include the integer part, the
fractional part, or both. The signed exponent is introduced by e or E.

Here are some examples of floating-point literals −

3.14159 // Legal
314159E-5L // Legal
610E // Illegal: incomplete exponent
310f // Illegal: no decimal or exponent
.e77 // Illegal: missing integer or fraction

Boolean Literals

The Boolean literals are of two types and they are part of standard C++ keywords −

 A value of true representing true.


 A value of false representing false.
Character Literals

Character literals are enclosed in single quotes. If the literal begins with L (uppercase only), it
is a wide character literal (e.g., L'x') and should be stored in wchar_t type of variable .
Otherwise, it is a narrow character literal (e.g., 'x') and can be stored in a simple variable of
char type.

A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a
universal character (e.g., '\u02C0').

There are certain characters in C++ when they are preceded by a backslash they will have
special meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a
list of some of such escape sequence codes −

Escape sequence Meaning

\\ \ character

\' ' character

\" " character

\? ? character

\a Alert or bell

\b Backspace

\f Form feed

\n Newline

\r Carriage return

\t Horizontal tab

\v Vertical tab

\ooo Octal number of one to three digits

\xhh . . . Hexadecimal number of one or more digits

Following is the example to show a few escape sequence characters −

#include <iostream>
using namespace std;

int main() {
cout << "Hello\tWorld\n\n";
return 0;
}

When the above code is compiled and executed, it produces the following result −

Hello World

String Literals

String literals are enclosed in double quotes. A string contains characters that are similar to
character literals: plain characters, escape sequences, and universal characters.

You can break a long line into multiple lines using string literals and separate them using
whitespaces.

Here are some examples of string literals. All the three forms are identical strings.

"hello, dear"

"hello, \

dear"

"hello, " "d" "ear"

1.3.2 Defining Constants


There are two simple ways in C++ to define constants −

 Using #define preprocessor.


 Using const keyword.

The #define Preprocessor

Following is the form to use #define preprocessor to define a constant −

#define identifier value

Following example explains it in detail −

#include <iostream>
using namespace std;

#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'

int main() {
int area;

area = LENGTH * WIDTH;


cout << area;
cout << NEWLINE;
return 0;
}

When the above code is compiled and executed, it produces the following result −

50

The const Keyword

The const prefix can be used to declare constants with a specific type as follows −

const type variable = value;

Following example explains it in detail −

#include <iostream>
using namespace std;

int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;

area = LENGTH * WIDTH;


cout << area;
cout << NEWLINE;
return 0;
}

When the above code is compiled and executed, it produces the following result −

50

Note that it is a good programming practice to define constants in CAPITALS.

2.4 Data Types


The data type of a variable is important because it determines the operations that are allowed and the range
of values that can be stored. C++ defines several types of data, and each type has unique characteristics.
Because data types differ, all variables must be declared prior to their use, and a variable declaration always
includes a type specifier. The compiler requires this information in order to generate correct code. In C++
there is no concept of a “type-less” variable.
E
S
fi
U
C
w
b
u
d
flo
,h
v
ti
rm
P
+
c
in
s
e
p
ty
a
D
A second reason that data types are important to C++ programming is that several of the basic types are
closely tied to the building blocks upon which the computer operates: bytes and words. Thus, C++ lets you
operate on the same types of data as does the CPU itself. This is one of the ways that C++ enables you to
write very efficient, system-level code.

The C++ Data Types


C++ provides built-in data types that correspond to integers, characters, floating-point values, and Boolean
values. These are the ways that data is commonly stored and manipulated by a program. As you will see later
in this book, C++ allows you to construct more sophisticated types, such as classes, structures, and
enumerations, but these too are ultimately composed of the built-in types.

Data types in C++ are categorised in three groups: Built-in, user-defined and Derived.
2.4.1 Primitive Data Types
The various primitive data types available in C++.

Integer: Variables of type int hold integer quantities that do not require fractional components.
Variables of this type are often used for controlling loops and conditional statements, and for
counting. Because they don’t have fractional components, operations on int quantities are much
faster than they are on floating-point types.Keyword used for integer data types is
i1111111nt. Integers typically requires 4 bytes of memory space and ranges from -
2147483648 to 2147483647. The difference between signed and unsigned integers is in the
way the high-order bit of the integer is interpreted. If a signed integer is specified, then the C++
compiler will generate code that assumes that the high-order bit of an integer is to be used as a sign
flag. If the sign flag is 0, then the number is positive; if it is 1, then the number is negative. Negative
numbers are almost always represented using the two’s complement approach. In this method, all
bits in the number (except the sign flag) are reversed, and then 1 is added to this number. Finally,
the sign flag is set to 1.

Character: Variables of type char hold 8-bit ASCII characters such as A, z, or G, or any other 8-bit quantity.
Character data type is used for storing characters. Keyword used for character data type
is char. Characters typically requires 1 byte of memory space and ranges from -128 to
127 or 0 to 255. To specify a character, you must enclose it between single quotes. Thus, this assigns X to
the variable ch:

char ch;

ch = 'X';

You can output a char value using a cout statement. For example, this line outputs the value in ch:
cout << "This is ch: " << ch;

This results in the following output:


This is ch: X

The char type can be modified with signed or unsigned. Technically, whether char is signed or unsigned by
default is implementation-defined. However, for most compilers char is signed. Character data type is used
for storing characters. Keyword used for character data type is char. Characters typically
requires 1 byte of memory space and ranges from -128 to 127 or 0 to 255.

Boolean: Boolean data type is used for storing boolean or logical values. A boolean
variable can store either true or false. Keyword used for boolean data type is bool. C++
defines two Boolean constants, true and false, which are the only two values that a bool value can have.
Before continuing, it is important to understand how true and false are defined by C++. One of the
fundamental concepts in C++ is that any nonzero value is interpreted as true and zero is false. This


 Floating Point Types: Variables of the types float and double are employed either when a
fractional component is required or when your application requires very large or small numbers.
Variables of the types float and double are employed either when a fractional component is required or
when your application requires very large or small numbers. The difference between a float and a
double variable is the magnitude of the largest (and smallest) number that each one can hold.
Floating Point data type is used for storing single precision floating point values or
decimal values. Keyword used for floating point data type is float. Float variables
typically requires 4 byte of memory space.

Double Floating Point data type is used for storing double precision floating point
values or decimal values. Keyword used for double floating point data type is double.
Double variables typically requires 8 byte of memory space. Typically, a double can store a
number approximately ten times larger than a float. Of the two, double is the most commonly used.
One reason for this is that many of the math functions in the C++ function library use double values.

 void: Void means without any value. void datatype represents a valueless entity. Void
data type is used for those function which does not returns a value.

 Wide Character: Wide character data type is also a character data type but this data
type has size greater than the normal 8-bit datatype. Represented by wchar_t. It is
generally 2 or 4 bytes long.

C++ allows certain of the basic types to have modifiers preceding them. A modifier alters the meaning of the
base type so that it more precisely fits the needs of various situations. The data type modifiers are listed here:

 signed

 unsigned

 long

 short

The modifiers signed, unsigned, long, and short can be applied to int. The modifiers signed and unsigned
can be applied to the char type. The type double can be modified by long. Table 2-1 shows all valid
combinations of the basic types and the type modifiers. The table also shows the guaranteed minimum
range for each type as specified by the ANSI/ISO C++ standard.
2.4.2 Derived Data Types
Data types that are derived from the built-in data types are known as derived data types. The
various derived data types provided by C++ are arrays, junctions, references and pointers.

 Array An array is a set of elements of the same data type that are referred to by the
same name. All the elements in an array are stored at contiguous (one after another)
memory locations and each element is accessed by a unique index or subscript value.
The subscript value indicates the position of an element in an array.
 Function A function is a self-contained program segment that carries out a specific
well-defined task. In C++, every program contains one or more functions which can be
invoked from other parts of a program, if required.
 Reference A reference is an alternative name for a variable. That is, a reference is an
alias for a variable in a program. A variable and its reference can be used
interchangeably in a program as both refer to the same memory location. Hence,
changes made to any of them (say, a variable) are reflected in the other (on a
reference).
 Pointer A pointer is a variable that can store the memory address of another variable.
Pointers allow to use the memory dynamically. That is, with the help of pointers,
memory can be allocated or de-allocated to the variables at run-time, thus, making a
program more efficient.
2.4.3 User-Defined Data Types
Various user-defined data types provided by C++ are structures, unions, enumerations and
classes.

Structure, Union andClass: Structure and union are the significant features of C language.
Structure and union provide a way to group similar or dissimilar data types referred to by a
single name. However, C++ has extended the concept of structure and union by incorporating
some new features in these data types to support object -oriented programming.

C++ offers a new user-defined data type known as class, which forms the basis of object-
oriented programming. A class acts as a template which defines the data and functions that are
included in an object of a class. Classes are declared using the keyword class. Once a class has
been declared, its object can be easily created.

Enumeration: An enumeration is a set of named integer constants that specify all the
permissible values that can be assigned to enumeration variables. These set of permissible
values are known as enumerators. For example, consider this statement.

enum country { India, Nepal, UN, China};       // declaring an

                                                                                     //  enum type

In this statement, an enumeration data-type country (country is a tag name) , consisting of


enumerators NEPAL, UN and so on, is declared. Note that these enumerators represent
integer values, so any arithmetic operation can be performed on them.

By default, the first enumerator in the enumeration data type is assigned the value zero. The
value of subsequent enumerators is one greater than the value of previoNepal enumerator.
Hence, the value of NEPAL is 0, value of UN is 1 and so on. However, these default integer
values can be overridden by assigning values explicitly to the enumerators

as shown here.

           enum country {NEPAL, UN=3, India, china} ;

In this declaration, the value of NEPAL is O by default, the value of UN is 3, India is 4 and
soon.

Once an enum type is declared, its variables can be declared Nepaling this statement.

           country countryl, country2;

These variables countryl, country2 can be assigned any of the values specified in enum
declaration only. For example, consider these statements.

                   countryl India; // valid


                   country2 Japan; // invalid

Though the enumerations are treated as integers internally in C++, the compiler issues a
warning, if an int value is assigned to an enum type. For example, consider these statements.

                                                       Country1 = 3;                  //warning

                                                       Country1 = UN;              / /valid

                                                       Country1 = (country) 3; / /valid

C++ also allows creating special type of enums known as anonymous enums, that is, enums
without using tag name as shown in this statement.

                                                     enum {NEPAL, UN=3, India, China};

The enumerators of an anonymous enum can be used directly in the program as shown here.

                                                     int count = NEPAL;

2.5 The typedef Keyword


 C++ provides a typedef feature that allows to define new data type names for existing data
types that may be built-in, derived or user-defined data types. Once the new name has been
defined, variables can be declared using this new name. For example, consider this
declaration.

                                               typedef int integer;

In this declaration, a new name integer is given to the data type into This new name now can
be used to declare integer variables as shown here.

                                                 integer i, j, k;

Note that the typedef is used in a program to contribute to the development of a clearer
program. Moreover, it also helps in making machine-dependent programs more portable.

2.6 OPERATORS
C++ has a rich set of operators. All C operators are valid in C++ also. An operator is a symbol
that tells the compiler to perform specific mathematical or logical manipulations. C++ is rich
in built-in operators and provide the following types of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators

2.6.1 Arithmetic Operators


There are following arithmetic operators supported by C++ language −

Assume variable A holds 10 and variable B holds 20, then −

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200

/ Divides numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after an B % A will give 0


integer division

++ Increment operator, increases integer value by A++ will give 11


one

-- Decrement operator, decreases integer value by A-- will give 9


one

2.6.2 Relational Operators


There are following relational operators supported by C++ language. Assume variable A holds
10 and variable B holds 20, then −

Operator Description Example

Checks if the values of two operands are equal or


== (A == B) is not true.
not, if yes then condition becomes true.

Checks if the values of two operands are equal or


!= not, if values are not equal then condition (A != B) is true.
becomes true.

> Checks if the value of left operand is greater than (A > B) is not true.
the value of right operand, if yes then condition
becomes true.

Checks if the value of left operand is less than the


< value of right operand, if yes then condition (A < B) is true.
becomes true.

Checks if the value of left operand is greater than


>= or equal to the value of right operand, if yes then (A >= B) is not true.
condition becomes true.

Checks if the value of left operand is less than or


<= equal to the value of right operand, if yes then (A <= B) is true.
condition becomes true.

2.6.3 Logical Operators


There are following logical operators supported by C++ language.Assume variable A holds 1
and variable B holds 0, then −

Operator Description Example

Called Logical AND operator. If both the


&& operands are non-zero, then condition becomes (A && B) is false.
true.

Called Logical OR Operator. If any of the two


|| operands is non-zero, then condition becomes (A || B) is true.
true.

Called Logical NOT Operator. Use to reverses the


! logical state of its operand. If a condition is true, !(A && B) is true.
then Logical NOT operator will make false.

2.6.4 Bitwise Operators


Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and
^ are as follows −

P q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0
1 0 0 1 1

Assume if A = 60; and B = 13; now in binary format they will be as follows −

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A  = 1100 0011

The Bitwise operators supported by C++ language are listed in the following table. Assume
variable A holds 60 and variable B holds 13, then −

Operator Description Example

Binary AND Operator copies a bit to the result if


& (A & B) will give 12 which is 0000 1100
it exists in both operands.

Binary OR Operator copies a bit if it exists in


| (A | B) will give 61 which is 0011 1101
either operand.

Binary XOR Operator copies the bit if it is set in


^ (A ^ B) will give 49 which is 0011 0001
one operand but not both.

Binary Ones Complement Operator is unary and (~A ) will give -61 which is 1100 0011 in 2's
~
has the effect of 'flipping' bits. complement form due to a signed binary number.

Binary Left Shift Operator. The left operands


<< value is moved left by the number of bits A << 2 will give 240 which is 1111 0000
specified by the right operand.

Binary Right Shift Operator. The left operands


>> value is moved right by the number of bits A >> 2 will give 15 which is 0000 1111
specified by the right operand.
2.6.5 Assignment Operators
There are following assignment operators supported by C++ language −

Operator Description Example

Simple assignment operator, Assigns values from


= C = A + B will assign value of A + B into C
right side operands to left side operand.

Add AND assignment operator, It adds right operand


+= to the left operand and assign the result to left C += A is equivalent to C = C + A
operand.

Subtract AND assignment operator, It subtracts right


-= operand from the left operand and assign the result to C -= A is equivalent to C = C – A
left operand.

Multiply AND assignment operator, It multiplies


*= right operand with the left operand and assign the C *= A is equivalent to C = C * A
result to left operand.

Divide AND assignment operator, It divides left


/= operand with the right operand and assign the result C /= A is equivalent to C = C / A
to left operand.

Modulus AND assignment operator, It takes modulus


%= using two operands and assign the result to left C %= A is equivalent to C = C % A
operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Moreover C++ introduces some new operators. Two of such are

< insertion or put- to


> extraction or get-from
apart from them there are
: :scope resolution operator
: :* pointer to member declarator

.* pointer to member access operator

->* member dereferencing operator


new memory allocation operator
delete memory release operator
endl line feed operator
setw field width operator
Last two often referred to as manipulator.
In addition C++ allows us to provide new definition to some of the built-in operators. That is,
several meaning can be given to an operator, depending upon the type of argument used. This
process is known as operator overloading.

2.6.6 Scope resolution operator


Like C, C++ is also a block structured language. Same variable can be used in different blocks. The
scope of the variables extends within the block where it was declared. e.g.
{
int x=10;
…………;
{
int x=1;
…………;
}
}
The two different declarations of x refer to two different memory locations containing different
values. Statement in the second block can’t refer to the variable declared in the first block. Blocks in
C++ are often nested.
e.g.-
{
int x=10;
…………;

{ block 2
int x=1; block 1
………;
}
…………;

}
Block 2 contained in Block 1. note that a declaration in the inner block hides the declaration in
outer block, therefore, each declaration of x causes it to refer to a different data object. Within
the inner block , the variable x will refer to the data object declared therein.

In C global version of a variable can’t be accessed from within the inner block. C++ resolves
this problem by introducing a new operator called scope resolution operator ( : : ). This can be
used to uncover a hidden variable.

: : variable-name

#inc lude< iostream .h>


int m=10;

int main(void)
{
int m=20;
cout<<” \n m in inner block :”<<m;
cout<<”\n uncovered m :”<<: :m;
}
output :
m in inner block : 20
uncovered m :10
A major application of the scope resolution operator is to identify the class to which a member
function belongs.

2.6.7 Member dereferencing operator


Accessing the class members through pointers is allowed in C++. In order to achieve this C++
provides a set of three pointer-to-member operators.

: :* pointer to member declarator.


to declare a pointer to a member of a class.
.* pointer to member access operator.

to access a member using object name and a pointer to that


member .
->* member dereferencing operator.
to access a member using a pointer to the object and a pointer to
the member.

e.g. consider the following class

class A

{
private : int m;

public : void show( );


}
we can define a pointer to the member m as follows:
int A : :*ip = & A ::m
the ip pointer thus created ,acts like a class member.

The phrase A : :* means “pointer-to-member of class A”.


The phrase &A : : m means “address of m member of class”.

Note that int *ip = &m is illegal for m is not simply an int data type.
The pointer ip can be used to access the member m inside member function or
friend function.

Suppose that a be an object of class A.


cout<< a.*ip;
cout<< a.m;
are equivalent.

Suppose ap is a pointer to the object a


i.e. ap = &a;

The operator ->* or dereferencing operator is used to access a member when we use pointers to
both member and object.

cout<< ap->m;

cout<<ap->*ip;
are equivalent.

2.6.8 Memory management operator


C uses malloc( ) and calloc( ) functions to allocate memory dynamically at run-time. Similarly it
uses the function free( ) to free dynamically allocated memory. Apart from supporting above
two, C++ also defines two unary operators new and delete those perform the task of allocating
and freeing the memory in a better way.

Since these operators manipulate memory on the free store, they are also known as free store
operator.
The new operator allocates sufficient memory to hold a data object with any 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 . e.g.

writing
int *p ;
float *q ;
p = new int;
q = new float;
int *ip = new int ;
also permissible.

General form :

pointer variable = new datatype ;

When a data object is no longer required, it is destroyed to release the memory space for re-use
using the delete operator.

The general form :

delete pointer variable ;


The pointer variable is the pointer points to a data objects created with new. delete p;

delete q;

In order to delete an entire array pointed by p following statement may be used

delete[ ].p ; / p points to an array


previous versions required size of the array to be specified.

2.6.9 Manipulators
Manipulators are operators that are used to format the data display. The most commonly used
manipulators are ‘endl’ and ‘setw’.

The ‘endl’ manipulators, when used in an output statement , causes a linefeed to be inserted. It
has almost same effect as that of ‘\n’.

e.g.
int m = 7;
cout<< m<<endl;
output screen
7

within the printing zone, to make output justified, ‘setw’ manipulator is used.
The manipulator setw(n) specifies a field width n for printing the value of the variable sum. The
value is right justified within the field as shown below –
out<< setw(5)<<m;
output screen

3 4 5

2.7 Control Structures


2.7.1 Decision Making Statements
Selection Statements :-There are two types of selection statements in C++ :

1. if statement

2. switch statement
if Statement : If statement have three forms

(a) if … else Statement :- It is useable, when we have to performs an action if a condition is True
and we have to perform a different action if the condition is false. The syntax of if…else statement
is:
if ( < conditional expression > )
{
< statement-1 or block-1>;
/ statements to be executed when conditional expression is true.
}
else
{
statement-2 or block-2>;

/ statements to be executed when conditional expression is false.

}
If the <conditional expression> is evaluated to true then the < statement-1 or block-1> (statement
under if ( ) block ) will be executed otherwise the <statement-2 or block-2> (statements under else
block) would be executed. if there exists only one program statement under if( ) block then we may
omit curly braces { }.
#include <iostream>
using namespace std;
int main ()

{
//local variable declaration:
int a = 100;
//check the boolean condition
if( a < 20 )
{

//if condition is true then print the following

cout << "a is less than 20;" << endl;


}
else
{

//if condition is false then print the following


cout << "a is not less than 20;" << endl;

}
cout << "value of a is : " << a << endl;
return 0;
}
a is not less than 20;
value of a is : 100

(b) Simple if statement:- The else part in if … else statement is optional, if we omit the else part then
it becomes simple if statement. This statement is usable, when we have to either perform an action if a
condition is True or skips the action if the condition is false. The syntax of simple if statement is:
if ( < conditional expression > )
{
< statement-1 or block-1>;
/ statements to be executed when conditional expression is true.
}
Here <statement-1 or block-1> will be executed only if <conditional expression > evaluates true. if there
exists only one program statement under if( ) block then curly braces { } may be omitted. Example:
#include <iostream>

using namespace std;


int main ()

{
// local variable declaration: int a=10;

// check the boolean condition if( a < 20 )


{
//if condition is true then print the following
cout << "a is less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
}
The output of the above code is:
As the value of a is less than 20 therefore the output of the above code is:
value of a is : 10
(c) The if-else-if ladder :-This statement allows you to test a number of mutually exclusive cases
and only execute one set of statements for which condition evaluates true first.
The syntax is:
If ( <condition -1> )

statement-1; // do something if condition-1 is satisfied (True)

else if ( <condition – 2 >)


statement-3 ; // do something if condition -2 is satisfied (True)

else if (<condition – 3 >)

statement-3 ;

else if( < condition – n >)

statement-n ;

else

statement-m ;

In the above syntax there are ladder of multiple conditions presented by each if( ) , all of these
conditions are mutually exclusive. If one of them would evaluates true then the statement followed that
condition will be executed and all the conditions below it would not be evaluated (checked).

Say suppose if condition-3 gets satisfy (i.e. evaluates true value for the condition), then
statement-3 gets executed and all other conditions below it would be discarded.

If none of the n if ( ) conditions gets satisfied then the last else part always gets executed. It is not
compulsory to add an else at the last of the ladder.

Example:
#include <iostream>
using namespace std;
int main ()
{
local variable declaration: int a = 100;
//check the boolean condition if( a == 10 )
{
//if condition is true then print the following
cout << "Value of a is 10" << endl;
}
else if( a == 20 )
{
//if else if condition is true
cout << "Value of a is 20" << endl;
}
else if( a == 30 )
{
//if else if condition is true
cout << "Value of a is 30" << endl;
}
else
{
// if none of the conditions is true
cout << "Value of a is not matching" << endl;
}
cout << "Exact value of a is : " << a << endl;
return 0;
}
The output of above code is:
Value of a is not matching
Exact value of a is : 100

Nested if Statement:- If an if statement is written in the if or else clause of another if statement then it
is known as nested if. Some possible syntax of nested if statements given below: Syntax 1:-

if ( <outer- condition > )


{
if ( <inner-condition> )
{
//some statements to be executed
/ on satisfaction of inner if ( )
condition. } // end of scope of inner if( )
//some statements to be executed

/ on satisfaction of outer if ( ) condition. }


// end of the scope of outer if( )

#include <iostream>
using namespace std;
int main ()
{
//local variable declaration: int a = 100;
int b = 200;
//check the boolean condition if( a == 100 )
{
//if condition is true then check the following
if( b == 200 )
{
//if condition is true then print the following
cout << "Value of a is 100 and b is 200" << endl;
}
}
cout << "Exact value of a is : " << a << endl;
cout << "Exact value of b is : " << b << endl;
return 0;
}
The output of above code is:
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200

2. switch Statement :-This is multi-branching statement. Syntax of this statement is as follows:


switch (expression/variable)
case value_1: statement -1;

break;
case value_2: statement -2;
break;

case value_n: statement -n;


break;
[ default: statement -m ]

}
Note: expression/variable should be integer or character type only.

When the switch statement is executed, the expression/variable is evaluated and control is transferred directly
to the statement whose case label value matches the value of expression/ variable. If none of the case label
value matches the value of expression/variable then only the statement following the default will be
executed. If no default statement is there and no match is found then no action take place. In this case control
is transferred to the statement that follows the switch statement.

Example
#include <iostream>
using namespace std;
int main ()
{
//local variable declaration: char grade = 'D';
switch(grade)
{
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;
return 0;
}
The output of above code is:
You passed
Your grade is D

Loops Types
A loop statement allows us to execute a statement or group of statements multiple times and following
is the general from of a loop statement in most of the programming languages:

C++ programming language provides the following type of loops to handle looping requirements.

There are mainly two types of loops:


1. Entry Controlled loops: In this type of loops the test condition is tested before
entering the loop body. For Loop and While Loop are entry controlled loops.
2. Exit Controlled Loops: In this type of loops the test condition is tested or evaluated at
the end of loop body. Therefore, the loop body will execute atleast once, irrespective
of whether the test condition is true or false. do – while loop is exit controlled loop.

Loop Type Description


while loop Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.

for loop Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.

do...while Like a ‘while’ statement, except that it tests the condition at the end of the loop
loop body.

nested loops You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’
loop.

for Loop

A for loop is a repetition control structure which allows us to write a loop that is executed a
specific number of times. The loop enables us to perform n number of steps together in one
line.
Syntax:

for (initialization expr; test expr; update expr)


{
// body of the loop
// statements we want to execute
}

In for loop, a loop variable is used to control the loop. First initialize this loop variable to
some value, then check whether this variable is less than or greater than counter value. If
statement is true, then loop body is executed and loop variable gets updated . Steps are
repeated till  exit condition comes.

 Initialization Expression: In this expression we have to initialize the loop counter to


some value. for example: int i=1;
 Test Expression: In this expression we have to test the condition. If the condition
evaluates to true then we will execute the body of loop and go to update expression
otherwise we will exit from the for loop. For example: i <= 10;
 Update Expression: After executing loop body this expression increments/decrements
the loop variable by some value. for example: i++;

Flow diagram

Example:
#include <iostream>
using namespace std;
 int main()
{
    for (int i = 1; i <= 5; i++)
    {
        cout << "Hello World\n";
    }
 
    return 0;
}
The output of the above code is
Hello World
Hello World
Hello World
Hello World
Hello World
While loop

while loop is also an entry controlled loop. In case of for loop the number of iterations is known beforehand,
i.e. the number of times the loop body is needed to be executed is known to us.  while loops are used in
situations where the exact number of iterations of loop is not known beforehand. The loop execution is
terminated on the basis of test condition. A while loop statement repeatedly executes a target
statement as long as a given condition is true.

The syntax of while loop is :

while (loop_condition)
{
Loop_body
}
Here, statement(s) may be a single statement or a block of statements. The condition
may be any expression, and true is any non-zero value. The loop iterates while the
condition is true.When the condition becomes false, program control passes to the line
immediately following the loop.

Flow Diagram

Example:

#include <iostream>
using namespace std;
int main ()
{
//Local variable declaration: int
a = 10;
//while loop execution
while( a < 20 )
{
cout << "value of a: " << a << endl; a+
+;
}
return 0;
}
The output of above code is:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

do...while loop

do-while loop is an exit-controlled loop i.e. it evaluates its loop_condition at the bottom of the loop after
executing its loop_body statements. It means that a do-while loop always executes at least once. A
do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time. The syntax of a do...while loop in C++ is:
do
{
statement(s);
}
while( condition );

In do-while loop first of all loop_body will be executed and then loop_condition will be evaluates if
loop_condition is true then loop_body will be executed again, When the loop_condition becomes false, the
program control passes to the statement after the loop_body.

Flow Diagram
Example

#include <iostream>

using namespace std;

int main ()

Local variable declaration: int a


= 10;

do loop execution

do

cout << "value of a: " << a << endl;

a = a + 1;

}while( a < 20 );

return 0;

You might also like