SlideShare une entreprise Scribd logo
1  sur  22
Télécharger pour lire hors ligne
INTRODUCTION OF C++, DATA TYPES

AND

OPERATORS

5-1

LEARNING OBJECTIVES
At the end of this chapter you will be able to understand :
Introduction and Feature of C++
Character and Token
Precedence and Associativity
Program Structure
Data Types and Operators
Variables and Their Scope
Expressions

5.1. INTRODUCTION OF C++
C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup
at AT and T Bell Laboratories USA, in the early 1980’s. Stroustrup, an admirer of
Simula67 and a strong supporter of C wanted to combine the best of both the languages
and create a more powerful language that could support object-oriented programming
features and still retain the power and elegance of C. The result was C++.

L

C++ is an object-oriented computer language used in the development
of enterprise and commercial applications.

5.1.1. Feature of C++. C++ is a superset of the ‘C’ programming language. It contain
following feature :
1. Object-oriented. The object-oriented features in C++ allow programmers to build
large programs with clarity, extensibility and ease of maintenance incorporating the spirit
and efficiency of C. The most important facilities that C++ adds on to C are classes,
inheritance, function overloading and operator overloading.
2. Classes. C++ support the concept of classes. A class is a user defined type. Classes
provide data hiding, initialization of data, dynamic typing, user controlled memory
5-2

INTRODUCTION OF C++, DATA TYPES

AND

OPERATORS

management. Classes extend the built-in capabilities of C++ able you in representing
and solving complex, real-world problems. A class is an organization of data and functions
which operate on them. Data structures are called data members and the functions are
called member functions, the combination of data members and member functions
constitute a data object or simply an object.
3. Data Abstractions. In C++, classes use the concepts of abstraction and are define
as a list of abstract attributes such as size, height, width, cost and methods that operate
on these attributes.
4. Inheritance. The mechanism of deriving a new class form a base class is called
inheritance. C++ support the feature of inheritance. It is the capability of one of the thing
to inherit capabilities or properties from another class.
5. Polymorphism. Polymorphism is one of the C++ polymorphism is the concept that
supports the capability of an object of class to behave differently in response to a message
action.
6. Portability. C++ and its standard libraries are designed for portability. The current
implementation will run on most systems that support C. C libraries can be used from a
C++ program, and most tools that support programming in C can be used with C++.
7. Versatile. C++ is a versatile language for handling very large programs. It is suitable
for virtually any programming task including development of editors, compilers, databases,
communication systems and any complex real-life application systems.

5.2. CHARACTER SET
C++ programs are a collection of character set, keywords, identifiers, literals, operators
and white space etc.

L

Character set is valid set of characters. A character set represent any
letter, digit or any other sign.

C++ has the following character set:
Letter
A-Z and a-z.
Digits
0 to 9.
Special Symbols
+,-,/,,(),{},[],=,!=<,>,"",;,&,$,?,-<=,>=,% etc and
other characters.
White space characters Space, horizontal, vertical, tab, newline

5.3. TOKEN
In a passage of text, individual words and punctuation marks are called token or lexical
elements.

L

The smallest individual unit of a C++ program is known as a token or a
lexical unit.
INTRODUCTION OF C++, DATA TYPES

AND

5-3

OPERATORS

C++ has following token:
1. Keywords.
2. Identifier.
3. Literals.
4. Separators.
5. Operators.
1. Keywords. In C++, Keywords are the reserved word that have special meaning to
the language compiler. We cannot use any of the following as identifiers in your programs.

L

Keywords are the reserved word that have special to the language
compiler they cannot use as identifiers in your program.

The C++ programming contain following keywords as shown in Table 5.1:
Table 5.1 C++ Keywords
asm

auto

bad_cast

bad_typeid

bool

break

case

catch

char

class

const

const_cast

continue

default

delete

do

double

dynamic_cast

else

enum

except

explicit

extern

false

finally

float

for

friend

goto

if

inline

int

long

mutable

namespace

new

operator

private

protected

public

register

reinterpret_cast

return

short

signed

sizeof

static

static_cast

unsigned

struct

switch

template

this

throw

true

try

type_info

typedef

typeid

typename

union

unsigned

using

virtual

void

volatile

wchar_t

while

2. Identifiers. An identifier may be in any sequence of uppercase and lowercase letters,
numbers or underscore.
• They must not begin with number.
• C++ is case sensitive programming language, so A is different identifier then a.
5-4

INTRODUCTION OF C++, DATA TYPES

L

AND

OPERATORS

Identifiers are used to represents the names of classes, functions and
variables constant, etc. in C++.

Some of the example of identifier is as following:
IndiaCon

number

value4

$my

this_is_val

Not/right

this is my var

Invalid identifier names include:
2Val

number-val

3. Constant. A constant value in C++ is created by using a literal.

L

Constants are data items that never change the value during the execution
of program.

C++ allows several kinds of literals:
Integer Constant:

1000, 45, 32, 34, -12, -45.

Character Constant:

‘x’, ‘a’, ‘v’, ‘p’

Floating Constant:

99.8,

String Constant:

“Hello C++”,“GGGC Bhopal”

Escape Sequences Constant:

An escape can be included in double-quotes as
“n”, or as part of a string.

67.567, 456.78, -908.98, 987.23

4. Separators. In C++ there are some characters that are used as separators. For
Example, one of the most important separators in C++ is parentheses, which is used to
contain the list of parameters in functions definition and method invocation. The table
5.2 shown the different separators name, symbol used, and their use in C++ technology.
Table 5.2 Separators in C++
Symbol

Separator Name Descriptions

;

Semi-colon

Used to terminates the C++ Statements.

()

Parentheses

Represent properties of function parameters.

{}

Braces

Used to define a block of code for classes, functions,
and scopes.

[]

Bracket

Used to declare array types.

,

Comma

Used for the separation of identifier in C++.

.

Dot

Used to separate package name form sub packages
name and classes.

=

Equal to sign.

Used for variable initializations.
INTRODUCTION OF C++, DATA TYPES

AND

5-5

OPERATORS

5. Operators. Operators are special symbols that perform mathematical or logical
operations on one, two, or three operands, and then return a result. For example :
+, –, *, ÷ etc.

5.4. PRECEDENCE AND ASSOCIATIVITY
Precedence and Associativity Rules together determine in what order the variables are
evaluated in an expression. The Table 5.3 describes Precedence and Associativity rules
of variable.
Table 5.3 Precedence and Associativity rules for variables
Operator Type

Operators

Postfix Operators

x++, x--

Unary prefix operators

Associativity
Unary postfix increment and
decrement operators associate
left to right, other unary operators
associate right to left

++x ,--x ,+x ,-x ~ ,!

Right to left

*, / ,%

Left to right

+ ,-

Left to right

Shift

<< ,>>

Left to right

Equality

= =, !=

Left to right

Bitwise/Logical AND

&

Left to right

Bitwise/Logical XOR

^

Left to right

Bitwise/Logical OR

|

Left to right

&&

Left to right

Conditional OR

||

Left to right

Conditional

?:

Right to left

Assignment

= ,+= ,-=, *= ,/= ,%= ,
<<= ,>>=, &= ,^= |=

Right to left

Multiplicative
Additive

Conditional AND
5-6

INTRODUCTION OF C++, DATA TYPES

AND

OPERATORS

5.5. PROGRAM STRUCTURE
In C++, the structure of program looks like this:
// This Program is Written By Pawan Thakur // comment section
#include<iostream.h>
#include<conio.h>
// preprocessor directives
void main ()
// Main function
{
clrscr();
cout<<"Hello, world."<<endl;
// body of Main function
getch();
}
// End of Main function

Output:
Hello, world.

1. Comment section. The programmer can use comment section for short explanations
of the source code itself or other comment. In above program the comment section
display the following comment:
// This Program is Written By Pawan Thakur

// comment section

2. Preprocessor directive. Lines beginning with a hash sign (#) are directives for the
preprocessor. They are not regular code lines with expressions but indications for the
compiler's preprocessor. For Ex.
#include<iostream.h>

In this case the first directive #include <iostream.h> tells the preprocessor to include the
iostream.h standard file.
3. Main function definition. The main function is the point by where all C++ programs
start their execution, independently of its location within the source code. It is essential
that all C++ programs have a main function.
void main()
{
------------------}

body of main

This line corresponds to the beginning of the definition of the main function. The word
main is followed in the code by a pair of parentheses (). That is because it is a function.
4. Body of main. It contains the set of statements. A statement is a simple or compound
expression that can actually produce some effect. C++ uses curly-braces {} to group
things together.
cout represents the standard output stream in C++, and the meaning of the entire statement
is to insert a sequence of characters into the standard output stream.
INTRODUCTION OF C++, DATA TYPES

AND

OPERATORS

5-7

cout<<"Hello, world."<<endl;

In this case, Hello World is the sequence of characters which display on screen. The
statement ends with a semicolon character (;). This character is used to mark the end of
the statement and in fact it must be included at the end of all expression statements in all
C++ programs.

5.6. DATA TYPES
There are five basic data type in C++: char, int, float, double and void. All other data type
in C++ is based upon on of these basic data types. Such data types are called derived
data types.

L

Data type specifies the size and type of values that can stored in computer
memory.

C++ support flowing data types :
1. Basic data type.
2. User defined data type.
3. Derived data type.
Data types in C++ under various categories are shown in Fig. 5.1

Fig. 5.1. Data Type in C++.
5-8

INTRODUCTION OF C++, DATA TYPES

AND

OPERATORS

5.6.1. Basic data type
Basic data types are also called fundamental or built in data type. The built data types in
C++ are categorized in to numeric and non-numeric. In further, numeric data type are of
two types:
1. Integer Type
2. Floating - Point
1. Integer Types. C++ supports the integer data type as they are short, int and long.
(a) Short Integers. The smallest integer you can store in a word is declared with the
short keyword followed by a name. Because a short integer is signed by default, it can
store a value that ranges from -32768 to 32767. The program 5.1 displays the example
short integer.
Program 5.1. Example of Short Integer Data Type
#include <iostream.h>
#include<conio.h>
void main()
{
clrscr();
short number1, number2;
cout << "Enter a number between -32768 and 32767: ";
cin >> number1;
cout << "Enter another number: ";
cin >> number2;
cout << "nThe numbers you entered weren";
cout << "tNumber 1: " << number1 << "n";
cout << "tNumber 2: " << number2 << "n";
getch();
}

Output:

(b) Integers. In C++, an integer is variable whose values are between
2,147,483,648 and 2,147,484,647. The value is also said to fit in a 32-bit range. The
program 5.2 displays the example integer data type.
INTRODUCTION OF C++, DATA TYPES

AND

OPERATORS

5-9

Program 5.2. Example of Integer Data Type
#include <iostream.h>
#include<conio.h>
void main()
{
clrscr();
int coordX, coordY, coordZ;
cout << "Enter the coordinates of point An";
cout << "Horizontal X = ";
cin >> coordX;
cout << "Vertical Y = ";
cin >> coordY;
cout << "Depth Z = ";
cin >> coordZ;
cout << "nOn a cartesian system, point A is located at";
cout << "ntX = " << coordX;
cout << "ntY = " << coordY;
cout << "ntZ = " << coordZ;
getch();
}

Output-:

(c) Long Integers. An integer variable whose value should be positive can also be
declared with the long keyword. The long keyword is a positive 32-bit integer whose
value ranges from 0 to 4,294,967,295. The program 5.3 displays the example integer
data type.
Program 5.3. Example of Long Integer Data Type
#include <iostream.h>
#include<conio.h>
void main()
{
clrscr();
long UArea;
unsigned long Population;
cout << "What is the area of the U? ";
cin >> UArea;
cout << "What is the population of the U? ";
cin >> Population;
cout << "nCharacteristics of the U";
5-10

INTRODUCTION OF C++, DATA TYPES

AND

OPERATORS

cout << "ntArea = " << UArea<< "ntPopulation = "
<< Population;
getch();
}

Output-:

2. Floating - Point. The integers we have used so far have the main limitation of not
allowing decimal values. C++ provides floating identifier values that would solve this
problem. Floating point is another type of integer, used to hold numbers containing decimal
parts such as 34.456 and -12.780, 15.89 etc. Float and Double are two types of floating
point variables in C++.
(a) Float. The most fundamental floating variable is declared with the float keyword.
The value typically fits in 32 bits (4 bytes). To declare a variable that would hold decimal
values we can use the float data type. The program 5.4 displays the example of float
data type.
Program 5.4. Example of Float Data Type
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
float side, perimeter, area;
cout<<"Enter the side of the square: ";
cin>>side;
perimeter = side * 4;
area = side * side;
cout<<"Characteristics of the square:";
cout<<"nSide: "<<side;
cout<<"nPerimeter: "<<perimeter;
cout<<"nArea: "<<area;
getch();
}
INTRODUCTION OF C++, DATA TYPES

AND

OPERATORS

5-11

Output-:

(b) Double. When a variable is larger than the float we can use double identifier. The
double-precision identifier is an 8 Byte. The program 5.5 displays the example of double
data type.
Program 5.5. Example of Double Data Type
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
double side, perimeter, area;
cout<<"Enter the side of the square: ";
cin>>side;
perimeter = side * 4;
area = side * side;
cout<<"Characteristics of the square:";
cout<<"nSide: "<<side;
cout<<"nPerimeter: "<<perimeter;
cout<<"nArea: "<<area;
getch();
}
Output :

3. Void. The void was introduce in ANSI C. It is use to specify the return type of function
when it is not returning any value and indicate and empty argument list to a function.
For example : void getsum (void) ;
5.6.2. Non-numeric data types
Non-numeric data types are of two kinds:
5-12

INTRODUCTION OF C++, DATA TYPES

AND

OPERATORS

(a) Character Type. C++ provide char data type, which is used to store character
value in computer memory. If the character is of a signed category we declare it as a
signed character. This type of variable would be an 8-bit integer whose value can range
from – 128 to + 127. The program 5.6 displays the example char data type.
Program 5.6. Char Data Type
#include<iostream.h>
#include<conio.h>
void main()
{
char Satisfaction, Answer;
signed char AgeCategory, size;
cout<<"From A to Z, enter a char : ";
cin>>Satisfaction;
cout<<"Age category(t=teen/a=Adult/s=Senior): ";
cin>>ageCategory;
cout<<"Are you drunk(y=Yes/n=No)? ";
cin>>answer;
cout<<"Enter your size(s=Small/m=Medium/l=Large): ";
cin>>size;
cout<<"nSatisfaction: "<<Satisfaction;
cout<<"nAge category: "<<AgeCategory;
cout<<"nYour answer: "<<Answer;
cout<<"nYour size: "<<Size;
getch();
}

Output-:

(b) Boolean Type. In C++, Boolean data type is used for logical values. It can have
only one value of two possible values, true or false. The program 5.7 displays the example
of boolean data type.
Program 5.7. Boolean Data Type
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
INTRODUCTION OF C++, DATA TYPES

AND

OPERATORS

5-13

bool MachineIsWorking = true;
cout<<"Since this machine is working, its value is"
<<MachineIsWorking<<endl;
MachineIsWorking = false;
cout<<"The machine has stopped operating."
<<"Now its value is "<<MachineIsWorking<<endl;
getch();
}

5.6.3. User define data type. User defined data type are those data type which is
defined by user. C++ support following user defined data type :
(a) Class. A class is user define data type, a C++ program can have definition of
different classes. A class contains variables and functions. Variables are called instances
and functions are called method. Class is a template, which declare and define methods
that are called by the objects of the classes.
(b) Structure. A structure is a collection of different types of variables works under one
name, providing a convenient means of keeping related information. For example a
student record is a collection of rollno, name, class, marks, grade etc.
(c) Union. A union is a memory location that is shared by two or more different variables
at different times.
(d) Enumeration. An alternative method for naming integer constants is often convenient
then constant. This can be achieved by creating enumeration using keyword enum. For
example, enum{Start, Pause, Play}.
5.6.4. Derived data type. From the built in data types other data type can be derived by
using the declaration operations. C++ support following non-primitive derived data type:
(a) Arrays. An array is a derived data type. It is a container object that holds a fixed
number of values of a single type.
(b) Function. Function is a derived data type. The brief introduction of function is in 6
chapter.
(c) Pointer. Pointer is special type of variable which hold the address of another variable.

5.7. VARIABLES
A variable is a place to store information. A variable is a location in your computer’s
memory in which you can store a value and from which you can later retrieve that value.

L

Variable represents named storage locations, whose value can be
manipulated during the execution of program.

There are some rules for variables declaration in C++. The name of a variable:
(a) They starts with an underscore "_" or a letter, lowercase or uppercase, such as
a letter from a to z or from A to Z. Examples are Name, gender, _Students,
pRice.
5-14

INTRODUCTION OF C++, DATA TYPES

AND

OPERATORS

(b) They can include letters, underscore, or digits. Examples are: keyboard, Master,
Junction, Player1, total_grade, _Score_Side1.
(c) They can not include special characters such as !, %, ] or $.
(d) They can not include an empty space.
(e) They can not be any of the reserved words.
The syntax to declare a new variable is to write the specified of the desired data type
(like int, bool, float.) followed by a valid variable identifier. For example:
int a;
float mynumber;

These are two valid declarations of variables. The first one declares a variable of type
int with the identifier a. The second one declares a variable of type float with the identifier
mynumber. Once declared, the variables a and mynumber can be used within their
scope in the program. The program 5.8 displays the example of variables.
Program 5.8. Example of variables
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a, b;
int result;
a = 5;
b = 2;
a = a + 1;
result = a - b;
cout<<result;
getch();
}

5.7.1. Scope of variables
All the variables that we want to use in a program must have been declared with its type
specifier. We have declared that a, b, and result were of type int, in the previous code at
the beginning of the body of the main().
A variable can be either of global or local scope.
(a) Global variable. A global variable is a variable declared in the main body of the
source code, outside all functions. Global variables can be used anywhere in the code,
after its declaration.
(b) Local variable. A local variable is one declared within the body of a function or a
block. The scope of local variables is limited to the block enclosed in braces {} where
INTRODUCTION OF C++, DATA TYPES

AND

OPERATORS

5-15

they are declared. For example, if they are declared at the beginning of the body of a
function their scope is between its declaration point and the end of that function.
The Fig. 5.2 displays the scope of local and global variables.

Fig. 5.2. Scopes of Variables.

5.8. OPERATORS IN C++
C++ provides rich collections of operator. The operations being carried out on data are
represented by operators.

L

Operators are special symbols that perform mathematical or logical
operations on one, two, or three operands, and then return a result.

Let us discuss these operators in details.
1. Arithmetic operators ( +, -, *, /, % ). The five arithmetical operations are supported
by the C++ language, as shown in table 5.4.
Table 5.4 Arithmetic operators
Operator

Descriptions

+

addition or unary plus

-

subtraction or unary minus

*

multiplication

/

division

%

modulus or module division

The operations of addition, subtraction, multiplication and division are done by the
mathematical operators.
5-16

INTRODUCTION OF C++, DATA TYPES

AND

OPERATORS

2. Relational operators and equality. The equality and relational operators are used
if one operand is greater than, less than, equal to or not equal to another operand. The
Table 5.5 describes the equality and relational operators and their descriptions.
Table5.3 Equality and Relational operators
Operator

Descriptions

==

Equal to

!=

Not equal to

>

Greater than

>=

Greater than or equal to

<

Less than

<=

Less than or equal to

The program 5.9 displays the example of relational operators.
Program 5.9. Example of relational operator
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a=10, b=3;
if(a>b)
cout<<"A is Greater";
getch();
}

Note: Keep in mind that you must use "==", not "=", when testing if two primitive values
are equal.
3. Assignment operator (=). The assignment operator assigns a value to a variable.
For Example: a = 5;
This statement assigns the integer value 5 to the variable a. The program 5.10 displays
the example of assignment operator.
Program 5.10. Example of assignment operator
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a, b;
INTRODUCTION OF C++, DATA TYPES

AND

5-17

OPERATORS

a = 10;
b = 4;
a = b;
b = 7;
cout<<"a:";
cout<<a;
cout<<" b:";
cout<<b;
getch();
}

4. Increment and decrement operator (++, --). In C++, the increase operator (++)
and the decrease operator (--) used to increase or reduce by one the value stored in a
variable. They are equivalent to +=1 and to -=1, respectively. Thus:
c++;
c+=1;
c=c+1;

The above three statements are all equivalent in its functionality increase by one the
value of c.
A characteristic of this operator is that it can be used both as a prefix and as a suffix.
That means that it can be written either before the variable identifier (++a) or after it
(a++). Although in simple expressions like a++ or ++a both have exactly the same
meaning. But other expressions in which the result of the increase or decrease operation
is evaluated as a value in an outer expression they may have an important difference in
their meaning: Notice the difference in table 5.6:
Table 5.6 Increase and decrease operator
Example 1

Example 2

B=3;
A=++B;
// A contain 4, B contain 4

B=3;
A=B++;
// A contain 3, B contain 4

In above table Example 1, B is increased before its value is copied to A. While in
Example 2, the value of B is copied to A and then B is increased.
5. Logical operators ( !, &&, || ). The && (AND), || (OR) and | (NOT) operators
perform Conditional-AND, Conditional-OR and Conditional-NOT operations on two
Boolean expressions. For example:
((5 = = 5)&&(3 > 6))//evaluates to false (true && false)
((5 = = 5)||(3 > 6))//evaluates to true (true || false)
5-18

INTRODUCTION OF C++, DATA TYPES

AND

OPERATORS

6. Conditional operator (? :). The conditional operator evaluates an expression returning
a value if that expression is true and a different one if the expression is evaluated as
false. Its format is:
condition ? result1 : result2

If condition is true, the expression will return result1, if it is not true it will return
result2. The program 5.11 displays the example of conditional operators.
Program 5.11. Example of conditional operators
#include<iostream.h>
#include<conio.h>
void main ()
{
clrscr();
int a,b,c;
a=2;
b=7;
c = (a>b) ? a : b;
cout << c;
getch();
}

In this example a is 2 and b is 7, the expression being evaluated (a>b) was not true, thus
the first value specified after the question mark was discarded in favor of the second
value (the one after the colon) which was b, with a value of 7.
7. Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=,^=, |=).
When we want to modify the value of a variable by performing an operation on the value
currently stored in that variable we can use compound assignment. The program 5.12
displays the example of assignment operator.
Program 5.12. Example of compound assignment operator
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a, b=3;
a = b;
a+=2; // equivalent to a=a+2
cout<<a;
getch();
}

8. Bitwise operators ( &, |, ^, ~, <<, >> ). Bitwise operators modify variables
considering the bit patterns that represent the values they store as shown in Table 5.7.
INTRODUCTION OF C++, DATA TYPES

AND

5-19

OPERATORS

Table 5.7. Bitwise Operators
Operator

Equivalent

Description

&

AND

Bitwise AND

|

OR

Bitwise Inclusive OR

^

XOR

Bitwise Exclusive OR

~

NOT

Unary Complement

<<

SHL

Shift Left

>>

SHR

Shift Right

9. The size of() operator. This operator accepts one parameter, which can be either a
type or a variable itself and returns the size in bytes of that type or object:
a = sizeof(char);

This will assign the value 1 to a because char is a one-byte long type. The value returned
by sizeof is a constant, so it is always determined before program execution.

5.9. EXPRESSIONS IN C++
In C++, anything that evaluates to a value is an expression. An expression is said to
return a value. Thus, 3 + 3 returns the value 6 and so is an expression. All expressions
are statements.

L

An expression in C++ is any valid combination of operators, constant
and variables.

A example of expression in C++:
x = a + b;

This is an expression not only adds a and b but also assigns the result to x and returns the
value of that assignment (the value of x) as well.
y = x = a + b;

This line is evaluated in the following order: Add a to b. Assign the result of the expression
a + b to x. Assign the result of the assignment expression x = a + b to y. If a, b, x, and y
are all integers, and if a has the value 2 and b has the value 5, both x and y will be
assigned the value 7. The program 5.12 displays the example of expressions.
5-20

INTRODUCTION OF C++, DATA TYPES

AND

OPERATORS

Program 5.13. Example of Expressions
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a=0, b=0, x=0, y=35;
cout<<"a: "<<a<<" b: "<<b;
cout<<" x: "<<x<<" y: "<<y<< endl;
a = 9;
b = 7;
y = x = a+b;
cout<<"a: "<<a<<" b: "<<b;
cout<<" x: "<<x<<" y: "<<y<< endl;
getch();
}

POINTS TO REMEMBER
(i) C++ is not a pure object oriented language.
(ii) Pure object oriented language purely deals with classes objects which means you
can not write even very simple program without using a class. If you want to
display “Hellow World” you have to write this with in class.
(iii) Java is pure object oriented language.
(iv) If you want to convert one data type to another data type you have to use type
cast.
(v) The small individual unit of C++ program is known as a token.
(vi) A constant value in C++ is created by using a literal.
(vii) Data type specifies the size and type of values that can stored in computer
memory.
(viii) The range of short integers is from – 32768 to 32767.
(ix) Class is user define data type.
(x) Operators are special symbols that perform mathematical or logical operation.

KEY TERMS
❍ Character set
❍ Identifiers
❍ Basic data type
❍ Integer type
❍ Boolean

❍ Token
❍ Constant
❍ User defined data type
❍ Floating type
❍ Character type
INTRODUCTION OF C++, DATA TYPES

AND

5-21

OPERATORS

❍ Derived data type
❍ Operator
❍ Increment and decrement

❍ Associativity and precedence
❍ Arithmetical and logical
❍ Assignment operator

MULTIPLE CHOICE QUESTIONS
1. A byte can store a relatively small amount of data
(a) One single character
(b) Double character
(c) Integer between 0 and 3267
(d) None of above
2. The smallest integer you can store in a word is declared with the
(a) Integer
(b) Short keyword
(c) Long integer
(d) None of above
3. The float is a real number of
(a) 2 Byte
(c) 8 Byte

(b) 4 Byte
(d) 16 Byte

4. The double is a real number of
(a) 2 Byte
(c) 8 Byte

(b) 4 Byte
(d) 16 Byte

5. To declare a variable as a character use the keyword
(a) String
(b) Char
(c) Character
(d) Array
6. The Boolean data type is used to declare a variable whose value would be set
as
(a) Numeric or character
(b) True (1) or False (0)
(c) Negative or positive
(d) None of above
7. A named location that stores a value is called
(a) Variable
(b) Character
(c) String
(d) Function
8. A global variable is a variable declared in the
(a) Main body of the source code (b) Inside the main function
(c) Inside a class
(d) Inside a user function
9. Anything that evaluates a value in C++.
(a) Statement
(b) Expression
(c) Method
(d) Operator
10. The symbol used to perform the Boolean operation NOT is.
(a) ||
(b) &&
(c) !
(d) << >>

⎫

⎭
5-22

INTRODUCTION OF C++, DATA TYPES

AND

OPERATORS

ANSWERS
1. (a)
6. (b)

2. (b)
7. (a)

3. (b)
8. (a)

4. (c)
9. (b)

5. (b)
10. (c)

UNSOLVED QUESTIONS
1. What is C++ ? Explain the features of C++.
2. Explain different token in C++.
3. Write down the structure of C++ program.
4. What do you mean by data type ? Explain different data type in C++.
5. What is the different between user defined and derived data type ?
6. Explain basic data type in C++.
7. What is variable ? Explain the scope of variables in C++.
8. What is operator ? Explain different type of operators in C++.
9. Explain the concept expression in C++.
10. What is the difference between C and C++ ?
❍❍❍

Contenu connexe

Tendances

C notes by m v b reddy(gitam)imp notes all units notes 5 unit order
C notes by m v b  reddy(gitam)imp  notes  all units notes  5 unit orderC notes by m v b  reddy(gitam)imp  notes  all units notes  5 unit order
C notes by m v b reddy(gitam)imp notes all units notes 5 unit order
Malikireddy Bramhananda Reddy
 
C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)
indrasir
 

Tendances (20)

C notes by m v b reddy(gitam)imp notes all units notes 5 unit order
C notes by m v b  reddy(gitam)imp  notes  all units notes  5 unit orderC notes by m v b  reddy(gitam)imp  notes  all units notes  5 unit order
C notes by m v b reddy(gitam)imp notes all units notes 5 unit order
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
Handout#04
Handout#04Handout#04
Handout#04
 
Handout#01
Handout#01Handout#01
Handout#01
 
Unit 2 introduction to c programming
Unit 2   introduction to c programmingUnit 2   introduction to c programming
Unit 2 introduction to c programming
 
Assignment11
Assignment11Assignment11
Assignment11
 
Top C Language Interview Questions and Answer
Top C Language Interview Questions and AnswerTop C Language Interview Questions and Answer
Top C Language Interview Questions and Answer
 
Handout#07
Handout#07Handout#07
Handout#07
 
Programming in c
Programming in cProgramming in c
Programming in c
 
C programming language Reference Note
C programming language Reference NoteC programming language Reference Note
C programming language Reference Note
 
C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)
 
Chapter2
Chapter2Chapter2
Chapter2
 
Report on c and c++
Report on c and c++Report on c and c++
Report on c and c++
 
Overview of c#
Overview of c#Overview of c#
Overview of c#
 
C programming
C programmingC programming
C programming
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
 
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTTC programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
 
Handout#06
Handout#06Handout#06
Handout#06
 
Handout#02
Handout#02Handout#02
Handout#02
 
C language
C language C language
C language
 

En vedette (13)

If you build it boolean tools
If you build it boolean toolsIf you build it boolean tools
If you build it boolean tools
 
Tim R Betts Resume
Tim R Betts ResumeTim R Betts Resume
Tim R Betts Resume
 
Curriculo PAULO BOMBONATTI - INGLES
Curriculo PAULO BOMBONATTI -  INGLESCurriculo PAULO BOMBONATTI -  INGLES
Curriculo PAULO BOMBONATTI - INGLES
 
CV1-Sadaf_Siddiqui
CV1-Sadaf_SiddiquiCV1-Sadaf_Siddiqui
CV1-Sadaf_Siddiqui
 
Sahil Gupta- Resume
Sahil Gupta- ResumeSahil Gupta- Resume
Sahil Gupta- Resume
 
C++ & VISUAL C++
C++ & VISUAL C++ C++ & VISUAL C++
C++ & VISUAL C++
 
Resume-Vishnu
Resume-VishnuResume-Vishnu
Resume-Vishnu
 
prasad_resume
prasad_resumeprasad_resume
prasad_resume
 
cv-julio_xavier
cv-julio_xaviercv-julio_xavier
cv-julio_xavier
 
Scott_Muller_Resume
Scott_Muller_ResumeScott_Muller_Resume
Scott_Muller_Resume
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
HIDAIPP
HIDAIPPHIDAIPP
HIDAIPP
 
VENKAT KALLAGUNTA_RESUME
VENKAT KALLAGUNTA_RESUMEVENKAT KALLAGUNTA_RESUME
VENKAT KALLAGUNTA_RESUME
 

Similaire à Introduction of C++ By Pawan Thakur

Chapter vvxxxxxxxxxxx1 - Part 1 (3).pptx
Chapter vvxxxxxxxxxxx1 - Part 1 (3).pptxChapter vvxxxxxxxxxxx1 - Part 1 (3).pptx
Chapter vvxxxxxxxxxxx1 - Part 1 (3).pptx
rajinevitable05
 
C programming language tutorial for beginers.pdf
C programming language tutorial for beginers.pdfC programming language tutorial for beginers.pdf
C programming language tutorial for beginers.pdf
ComedyTechnology
 

Similaire à Introduction of C++ By Pawan Thakur (20)

Chapter vvxxxxxxxxxxx1 - Part 1 (3).pptx
Chapter vvxxxxxxxxxxx1 - Part 1 (3).pptxChapter vvxxxxxxxxxxx1 - Part 1 (3).pptx
Chapter vvxxxxxxxxxxx1 - Part 1 (3).pptx
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
CP c++ programing project Unit 1 intro.pdf
CP c++ programing project  Unit 1 intro.pdfCP c++ programing project  Unit 1 intro.pdf
CP c++ programing project Unit 1 intro.pdf
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++
 
Introduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to itIntroduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to it
 
C programming Training in Ambala ! Batra Computer Centre
C programming Training in Ambala ! Batra Computer CentreC programming Training in Ambala ! Batra Computer Centre
C programming Training in Ambala ! Batra Computer Centre
 
UNIT 1 NOTES.docx
UNIT 1 NOTES.docxUNIT 1 NOTES.docx
UNIT 1 NOTES.docx
 
Interview Questions For C Language
Interview Questions For C Language Interview Questions For C Language
Interview Questions For C Language
 
Interview Questions For C Language .pptx
Interview Questions For C Language .pptxInterview Questions For C Language .pptx
Interview Questions For C Language .pptx
 
The C++ Programming Language
The C++ Programming LanguageThe C++ Programming Language
The C++ Programming Language
 
Aniket tore
Aniket toreAniket tore
Aniket tore
 
Unit 1.1 - Introduction to C.pptx
Unit 1.1 - Introduction to C.pptxUnit 1.1 - Introduction to C.pptx
Unit 1.1 - Introduction to C.pptx
 
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTRE
C++  Langauage Training in Ambala ! BATRA COMPUTER CENTREC++  Langauage Training in Ambala ! BATRA COMPUTER CENTRE
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTRE
 
c_programming.pdf
c_programming.pdfc_programming.pdf
c_programming.pdf
 
Cp week _2.
Cp week _2.Cp week _2.
Cp week _2.
 
1. introduction to computer
1. introduction to computer1. introduction to computer
1. introduction to computer
 
Lecture 1 progrmming with C
Lecture 1 progrmming with C Lecture 1 progrmming with C
Lecture 1 progrmming with C
 
C programming language tutorial for beginers.pdf
C programming language tutorial for beginers.pdfC programming language tutorial for beginers.pdf
C programming language tutorial for beginers.pdf
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 

Plus de Govt. P.G. College Dharamshala

Internet of Things
Internet of ThingsInternet of Things
Internet of Things
Govt. P.G. College Dharamshala
 
cloud computing
cloud computing cloud computing

Plus de Govt. P.G. College Dharamshala (20)

Dr. vikas saraf shop3
Dr. vikas saraf shop3Dr. vikas saraf shop3
Dr. vikas saraf shop3
 
Dr. vikas saraf shop2
Dr. vikas saraf shop2Dr. vikas saraf shop2
Dr. vikas saraf shop2
 
Dr. vikas saraf shop1
Dr. vikas saraf shop1Dr. vikas saraf shop1
Dr. vikas saraf shop1
 
Internet of Things
Internet of ThingsInternet of Things
Internet of Things
 
Contents of Internet of Things(IoT) By Thakur Pawan & Pathania Susheela
Contents of Internet of Things(IoT) By Thakur Pawan & Pathania SusheelaContents of Internet of Things(IoT) By Thakur Pawan & Pathania Susheela
Contents of Internet of Things(IoT) By Thakur Pawan & Pathania Susheela
 
Introduction of Internet of Things(IoT) By Thakur Pawan & Pathania Susheela
Introduction of Internet of Things(IoT) By Thakur Pawan & Pathania SusheelaIntroduction of Internet of Things(IoT) By Thakur Pawan & Pathania Susheela
Introduction of Internet of Things(IoT) By Thakur Pawan & Pathania Susheela
 
PUBG MOBILE – APPS: A CRITICAL REVIEW BY ANSHUL VERMA
PUBG MOBILE – APPS: A CRITICAL REVIEW BY ANSHUL VERMAPUBG MOBILE – APPS: A CRITICAL REVIEW BY ANSHUL VERMA
PUBG MOBILE – APPS: A CRITICAL REVIEW BY ANSHUL VERMA
 
Cloud Infrastructure m Service Delivery Models (IAAS, PAAS and SAAS) Cloud D...
Cloud Infrastructure m Service Delivery Models (IAAS, PAAS and SAAS)  Cloud D...Cloud Infrastructure m Service Delivery Models (IAAS, PAAS and SAAS)  Cloud D...
Cloud Infrastructure m Service Delivery Models (IAAS, PAAS and SAAS) Cloud D...
 
cloud computing
cloud computing cloud computing
cloud computing
 
Introduction of cloud By Pawan Thakur
Introduction of cloud By Pawan ThakurIntroduction of cloud By Pawan Thakur
Introduction of cloud By Pawan Thakur
 
Introduction to computer in Hindi By Pawan Thakur
Introduction to computer in Hindi  By Pawan ThakurIntroduction to computer in Hindi  By Pawan Thakur
Introduction to computer in Hindi By Pawan Thakur
 
Computer in hindi I
Computer in hindi IComputer in hindi I
Computer in hindi I
 
Introduction of computer in hindi II
Introduction of computer in hindi  IIIntroduction of computer in hindi  II
Introduction of computer in hindi II
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
 
Operating System
Operating SystemOperating System
Operating System
 
Basics of Computer
Basics of Computer Basics of Computer
Basics of Computer
 
Saraf & Thakur
Saraf  & ThakurSaraf  & Thakur
Saraf & Thakur
 
Computer Network By Pawan Thakur HOD CS & IT VIM BHOPAL
Computer Network By Pawan Thakur HOD CS & IT VIM BHOPALComputer Network By Pawan Thakur HOD CS & IT VIM BHOPAL
Computer Network By Pawan Thakur HOD CS & IT VIM BHOPAL
 
Analysis of mutual exclusion algorithms with the significance and need of ele...
Analysis of mutual exclusion algorithms with the significance and need of ele...Analysis of mutual exclusion algorithms with the significance and need of ele...
Analysis of mutual exclusion algorithms with the significance and need of ele...
 
0Pawan Thakur
0Pawan Thakur0Pawan Thakur
0Pawan Thakur
 

Dernier

Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Dernier (20)

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 

Introduction of C++ By Pawan Thakur

  • 1. INTRODUCTION OF C++, DATA TYPES AND OPERATORS 5-1 LEARNING OBJECTIVES At the end of this chapter you will be able to understand : Introduction and Feature of C++ Character and Token Precedence and Associativity Program Structure Data Types and Operators Variables and Their Scope Expressions 5.1. INTRODUCTION OF C++ C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT and T Bell Laboratories USA, in the early 1980’s. Stroustrup, an admirer of Simula67 and a strong supporter of C wanted to combine the best of both the languages and create a more powerful language that could support object-oriented programming features and still retain the power and elegance of C. The result was C++. L C++ is an object-oriented computer language used in the development of enterprise and commercial applications. 5.1.1. Feature of C++. C++ is a superset of the ‘C’ programming language. It contain following feature : 1. Object-oriented. The object-oriented features in C++ allow programmers to build large programs with clarity, extensibility and ease of maintenance incorporating the spirit and efficiency of C. The most important facilities that C++ adds on to C are classes, inheritance, function overloading and operator overloading. 2. Classes. C++ support the concept of classes. A class is a user defined type. Classes provide data hiding, initialization of data, dynamic typing, user controlled memory
  • 2. 5-2 INTRODUCTION OF C++, DATA TYPES AND OPERATORS management. Classes extend the built-in capabilities of C++ able you in representing and solving complex, real-world problems. A class is an organization of data and functions which operate on them. Data structures are called data members and the functions are called member functions, the combination of data members and member functions constitute a data object or simply an object. 3. Data Abstractions. In C++, classes use the concepts of abstraction and are define as a list of abstract attributes such as size, height, width, cost and methods that operate on these attributes. 4. Inheritance. The mechanism of deriving a new class form a base class is called inheritance. C++ support the feature of inheritance. It is the capability of one of the thing to inherit capabilities or properties from another class. 5. Polymorphism. Polymorphism is one of the C++ polymorphism is the concept that supports the capability of an object of class to behave differently in response to a message action. 6. Portability. C++ and its standard libraries are designed for portability. The current implementation will run on most systems that support C. C libraries can be used from a C++ program, and most tools that support programming in C can be used with C++. 7. Versatile. C++ is a versatile language for handling very large programs. It is suitable for virtually any programming task including development of editors, compilers, databases, communication systems and any complex real-life application systems. 5.2. CHARACTER SET C++ programs are a collection of character set, keywords, identifiers, literals, operators and white space etc. L Character set is valid set of characters. A character set represent any letter, digit or any other sign. C++ has the following character set: Letter A-Z and a-z. Digits 0 to 9. Special Symbols +,-,/,,(),{},[],=,!=<,>,"",;,&,$,?,-<=,>=,% etc and other characters. White space characters Space, horizontal, vertical, tab, newline 5.3. TOKEN In a passage of text, individual words and punctuation marks are called token or lexical elements. L The smallest individual unit of a C++ program is known as a token or a lexical unit.
  • 3. INTRODUCTION OF C++, DATA TYPES AND 5-3 OPERATORS C++ has following token: 1. Keywords. 2. Identifier. 3. Literals. 4. Separators. 5. Operators. 1. Keywords. In C++, Keywords are the reserved word that have special meaning to the language compiler. We cannot use any of the following as identifiers in your programs. L Keywords are the reserved word that have special to the language compiler they cannot use as identifiers in your program. The C++ programming contain following keywords as shown in Table 5.1: Table 5.1 C++ Keywords asm auto bad_cast bad_typeid bool break case catch char class const const_cast continue default delete do double dynamic_cast else enum except explicit extern false finally float for friend goto if inline int long mutable namespace new operator private protected public register reinterpret_cast return short signed sizeof static static_cast unsigned struct switch template this throw true try type_info typedef typeid typename union unsigned using virtual void volatile wchar_t while 2. Identifiers. An identifier may be in any sequence of uppercase and lowercase letters, numbers or underscore. • They must not begin with number. • C++ is case sensitive programming language, so A is different identifier then a.
  • 4. 5-4 INTRODUCTION OF C++, DATA TYPES L AND OPERATORS Identifiers are used to represents the names of classes, functions and variables constant, etc. in C++. Some of the example of identifier is as following: IndiaCon number value4 $my this_is_val Not/right this is my var Invalid identifier names include: 2Val number-val 3. Constant. A constant value in C++ is created by using a literal. L Constants are data items that never change the value during the execution of program. C++ allows several kinds of literals: Integer Constant: 1000, 45, 32, 34, -12, -45. Character Constant: ‘x’, ‘a’, ‘v’, ‘p’ Floating Constant: 99.8, String Constant: “Hello C++”,“GGGC Bhopal” Escape Sequences Constant: An escape can be included in double-quotes as “n”, or as part of a string. 67.567, 456.78, -908.98, 987.23 4. Separators. In C++ there are some characters that are used as separators. For Example, one of the most important separators in C++ is parentheses, which is used to contain the list of parameters in functions definition and method invocation. The table 5.2 shown the different separators name, symbol used, and their use in C++ technology. Table 5.2 Separators in C++ Symbol Separator Name Descriptions ; Semi-colon Used to terminates the C++ Statements. () Parentheses Represent properties of function parameters. {} Braces Used to define a block of code for classes, functions, and scopes. [] Bracket Used to declare array types. , Comma Used for the separation of identifier in C++. . Dot Used to separate package name form sub packages name and classes. = Equal to sign. Used for variable initializations.
  • 5. INTRODUCTION OF C++, DATA TYPES AND 5-5 OPERATORS 5. Operators. Operators are special symbols that perform mathematical or logical operations on one, two, or three operands, and then return a result. For example : +, –, *, ÷ etc. 5.4. PRECEDENCE AND ASSOCIATIVITY Precedence and Associativity Rules together determine in what order the variables are evaluated in an expression. The Table 5.3 describes Precedence and Associativity rules of variable. Table 5.3 Precedence and Associativity rules for variables Operator Type Operators Postfix Operators x++, x-- Unary prefix operators Associativity Unary postfix increment and decrement operators associate left to right, other unary operators associate right to left ++x ,--x ,+x ,-x ~ ,! Right to left *, / ,% Left to right + ,- Left to right Shift << ,>> Left to right Equality = =, != Left to right Bitwise/Logical AND & Left to right Bitwise/Logical XOR ^ Left to right Bitwise/Logical OR | Left to right && Left to right Conditional OR || Left to right Conditional ?: Right to left Assignment = ,+= ,-=, *= ,/= ,%= , <<= ,>>=, &= ,^= |= Right to left Multiplicative Additive Conditional AND
  • 6. 5-6 INTRODUCTION OF C++, DATA TYPES AND OPERATORS 5.5. PROGRAM STRUCTURE In C++, the structure of program looks like this: // This Program is Written By Pawan Thakur // comment section #include<iostream.h> #include<conio.h> // preprocessor directives void main () // Main function { clrscr(); cout<<"Hello, world."<<endl; // body of Main function getch(); } // End of Main function Output: Hello, world. 1. Comment section. The programmer can use comment section for short explanations of the source code itself or other comment. In above program the comment section display the following comment: // This Program is Written By Pawan Thakur // comment section 2. Preprocessor directive. Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code lines with expressions but indications for the compiler's preprocessor. For Ex. #include<iostream.h> In this case the first directive #include <iostream.h> tells the preprocessor to include the iostream.h standard file. 3. Main function definition. The main function is the point by where all C++ programs start their execution, independently of its location within the source code. It is essential that all C++ programs have a main function. void main() { ------------------} body of main This line corresponds to the beginning of the definition of the main function. The word main is followed in the code by a pair of parentheses (). That is because it is a function. 4. Body of main. It contains the set of statements. A statement is a simple or compound expression that can actually produce some effect. C++ uses curly-braces {} to group things together. cout represents the standard output stream in C++, and the meaning of the entire statement is to insert a sequence of characters into the standard output stream.
  • 7. INTRODUCTION OF C++, DATA TYPES AND OPERATORS 5-7 cout<<"Hello, world."<<endl; In this case, Hello World is the sequence of characters which display on screen. The statement ends with a semicolon character (;). This character is used to mark the end of the statement and in fact it must be included at the end of all expression statements in all C++ programs. 5.6. DATA TYPES There are five basic data type in C++: char, int, float, double and void. All other data type in C++ is based upon on of these basic data types. Such data types are called derived data types. L Data type specifies the size and type of values that can stored in computer memory. C++ support flowing data types : 1. Basic data type. 2. User defined data type. 3. Derived data type. Data types in C++ under various categories are shown in Fig. 5.1 Fig. 5.1. Data Type in C++.
  • 8. 5-8 INTRODUCTION OF C++, DATA TYPES AND OPERATORS 5.6.1. Basic data type Basic data types are also called fundamental or built in data type. The built data types in C++ are categorized in to numeric and non-numeric. In further, numeric data type are of two types: 1. Integer Type 2. Floating - Point 1. Integer Types. C++ supports the integer data type as they are short, int and long. (a) Short Integers. The smallest integer you can store in a word is declared with the short keyword followed by a name. Because a short integer is signed by default, it can store a value that ranges from -32768 to 32767. The program 5.1 displays the example short integer. Program 5.1. Example of Short Integer Data Type #include <iostream.h> #include<conio.h> void main() { clrscr(); short number1, number2; cout << "Enter a number between -32768 and 32767: "; cin >> number1; cout << "Enter another number: "; cin >> number2; cout << "nThe numbers you entered weren"; cout << "tNumber 1: " << number1 << "n"; cout << "tNumber 2: " << number2 << "n"; getch(); } Output: (b) Integers. In C++, an integer is variable whose values are between 2,147,483,648 and 2,147,484,647. The value is also said to fit in a 32-bit range. The program 5.2 displays the example integer data type.
  • 9. INTRODUCTION OF C++, DATA TYPES AND OPERATORS 5-9 Program 5.2. Example of Integer Data Type #include <iostream.h> #include<conio.h> void main() { clrscr(); int coordX, coordY, coordZ; cout << "Enter the coordinates of point An"; cout << "Horizontal X = "; cin >> coordX; cout << "Vertical Y = "; cin >> coordY; cout << "Depth Z = "; cin >> coordZ; cout << "nOn a cartesian system, point A is located at"; cout << "ntX = " << coordX; cout << "ntY = " << coordY; cout << "ntZ = " << coordZ; getch(); } Output-: (c) Long Integers. An integer variable whose value should be positive can also be declared with the long keyword. The long keyword is a positive 32-bit integer whose value ranges from 0 to 4,294,967,295. The program 5.3 displays the example integer data type. Program 5.3. Example of Long Integer Data Type #include <iostream.h> #include<conio.h> void main() { clrscr(); long UArea; unsigned long Population; cout << "What is the area of the U? "; cin >> UArea; cout << "What is the population of the U? "; cin >> Population; cout << "nCharacteristics of the U";
  • 10. 5-10 INTRODUCTION OF C++, DATA TYPES AND OPERATORS cout << "ntArea = " << UArea<< "ntPopulation = " << Population; getch(); } Output-: 2. Floating - Point. The integers we have used so far have the main limitation of not allowing decimal values. C++ provides floating identifier values that would solve this problem. Floating point is another type of integer, used to hold numbers containing decimal parts such as 34.456 and -12.780, 15.89 etc. Float and Double are two types of floating point variables in C++. (a) Float. The most fundamental floating variable is declared with the float keyword. The value typically fits in 32 bits (4 bytes). To declare a variable that would hold decimal values we can use the float data type. The program 5.4 displays the example of float data type. Program 5.4. Example of Float Data Type #include<iostream.h> #include<conio.h> void main() { clrscr(); float side, perimeter, area; cout<<"Enter the side of the square: "; cin>>side; perimeter = side * 4; area = side * side; cout<<"Characteristics of the square:"; cout<<"nSide: "<<side; cout<<"nPerimeter: "<<perimeter; cout<<"nArea: "<<area; getch(); }
  • 11. INTRODUCTION OF C++, DATA TYPES AND OPERATORS 5-11 Output-: (b) Double. When a variable is larger than the float we can use double identifier. The double-precision identifier is an 8 Byte. The program 5.5 displays the example of double data type. Program 5.5. Example of Double Data Type #include<iostream.h> #include<conio.h> void main() { clrscr(); double side, perimeter, area; cout<<"Enter the side of the square: "; cin>>side; perimeter = side * 4; area = side * side; cout<<"Characteristics of the square:"; cout<<"nSide: "<<side; cout<<"nPerimeter: "<<perimeter; cout<<"nArea: "<<area; getch(); } Output : 3. Void. The void was introduce in ANSI C. It is use to specify the return type of function when it is not returning any value and indicate and empty argument list to a function. For example : void getsum (void) ; 5.6.2. Non-numeric data types Non-numeric data types are of two kinds:
  • 12. 5-12 INTRODUCTION OF C++, DATA TYPES AND OPERATORS (a) Character Type. C++ provide char data type, which is used to store character value in computer memory. If the character is of a signed category we declare it as a signed character. This type of variable would be an 8-bit integer whose value can range from – 128 to + 127. The program 5.6 displays the example char data type. Program 5.6. Char Data Type #include<iostream.h> #include<conio.h> void main() { char Satisfaction, Answer; signed char AgeCategory, size; cout<<"From A to Z, enter a char : "; cin>>Satisfaction; cout<<"Age category(t=teen/a=Adult/s=Senior): "; cin>>ageCategory; cout<<"Are you drunk(y=Yes/n=No)? "; cin>>answer; cout<<"Enter your size(s=Small/m=Medium/l=Large): "; cin>>size; cout<<"nSatisfaction: "<<Satisfaction; cout<<"nAge category: "<<AgeCategory; cout<<"nYour answer: "<<Answer; cout<<"nYour size: "<<Size; getch(); } Output-: (b) Boolean Type. In C++, Boolean data type is used for logical values. It can have only one value of two possible values, true or false. The program 5.7 displays the example of boolean data type. Program 5.7. Boolean Data Type #include<iostream.h> #include<conio.h> void main() { clrscr();
  • 13. INTRODUCTION OF C++, DATA TYPES AND OPERATORS 5-13 bool MachineIsWorking = true; cout<<"Since this machine is working, its value is" <<MachineIsWorking<<endl; MachineIsWorking = false; cout<<"The machine has stopped operating." <<"Now its value is "<<MachineIsWorking<<endl; getch(); } 5.6.3. User define data type. User defined data type are those data type which is defined by user. C++ support following user defined data type : (a) Class. A class is user define data type, a C++ program can have definition of different classes. A class contains variables and functions. Variables are called instances and functions are called method. Class is a template, which declare and define methods that are called by the objects of the classes. (b) Structure. A structure is a collection of different types of variables works under one name, providing a convenient means of keeping related information. For example a student record is a collection of rollno, name, class, marks, grade etc. (c) Union. A union is a memory location that is shared by two or more different variables at different times. (d) Enumeration. An alternative method for naming integer constants is often convenient then constant. This can be achieved by creating enumeration using keyword enum. For example, enum{Start, Pause, Play}. 5.6.4. Derived data type. From the built in data types other data type can be derived by using the declaration operations. C++ support following non-primitive derived data type: (a) Arrays. An array is a derived data type. It is a container object that holds a fixed number of values of a single type. (b) Function. Function is a derived data type. The brief introduction of function is in 6 chapter. (c) Pointer. Pointer is special type of variable which hold the address of another variable. 5.7. VARIABLES A variable is a place to store information. A variable is a location in your computer’s memory in which you can store a value and from which you can later retrieve that value. L Variable represents named storage locations, whose value can be manipulated during the execution of program. There are some rules for variables declaration in C++. The name of a variable: (a) They starts with an underscore "_" or a letter, lowercase or uppercase, such as a letter from a to z or from A to Z. Examples are Name, gender, _Students, pRice.
  • 14. 5-14 INTRODUCTION OF C++, DATA TYPES AND OPERATORS (b) They can include letters, underscore, or digits. Examples are: keyboard, Master, Junction, Player1, total_grade, _Score_Side1. (c) They can not include special characters such as !, %, ] or $. (d) They can not include an empty space. (e) They can not be any of the reserved words. The syntax to declare a new variable is to write the specified of the desired data type (like int, bool, float.) followed by a valid variable identifier. For example: int a; float mynumber; These are two valid declarations of variables. The first one declares a variable of type int with the identifier a. The second one declares a variable of type float with the identifier mynumber. Once declared, the variables a and mynumber can be used within their scope in the program. The program 5.8 displays the example of variables. Program 5.8. Example of variables #include<iostream.h> #include<conio.h> void main() { clrscr(); int a, b; int result; a = 5; b = 2; a = a + 1; result = a - b; cout<<result; getch(); } 5.7.1. Scope of variables All the variables that we want to use in a program must have been declared with its type specifier. We have declared that a, b, and result were of type int, in the previous code at the beginning of the body of the main(). A variable can be either of global or local scope. (a) Global variable. A global variable is a variable declared in the main body of the source code, outside all functions. Global variables can be used anywhere in the code, after its declaration. (b) Local variable. A local variable is one declared within the body of a function or a block. The scope of local variables is limited to the block enclosed in braces {} where
  • 15. INTRODUCTION OF C++, DATA TYPES AND OPERATORS 5-15 they are declared. For example, if they are declared at the beginning of the body of a function their scope is between its declaration point and the end of that function. The Fig. 5.2 displays the scope of local and global variables. Fig. 5.2. Scopes of Variables. 5.8. OPERATORS IN C++ C++ provides rich collections of operator. The operations being carried out on data are represented by operators. L Operators are special symbols that perform mathematical or logical operations on one, two, or three operands, and then return a result. Let us discuss these operators in details. 1. Arithmetic operators ( +, -, *, /, % ). The five arithmetical operations are supported by the C++ language, as shown in table 5.4. Table 5.4 Arithmetic operators Operator Descriptions + addition or unary plus - subtraction or unary minus * multiplication / division % modulus or module division The operations of addition, subtraction, multiplication and division are done by the mathematical operators.
  • 16. 5-16 INTRODUCTION OF C++, DATA TYPES AND OPERATORS 2. Relational operators and equality. The equality and relational operators are used if one operand is greater than, less than, equal to or not equal to another operand. The Table 5.5 describes the equality and relational operators and their descriptions. Table5.3 Equality and Relational operators Operator Descriptions == Equal to != Not equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to The program 5.9 displays the example of relational operators. Program 5.9. Example of relational operator #include<iostream.h> #include<conio.h> void main() { clrscr(); int a=10, b=3; if(a>b) cout<<"A is Greater"; getch(); } Note: Keep in mind that you must use "==", not "=", when testing if two primitive values are equal. 3. Assignment operator (=). The assignment operator assigns a value to a variable. For Example: a = 5; This statement assigns the integer value 5 to the variable a. The program 5.10 displays the example of assignment operator. Program 5.10. Example of assignment operator #include<iostream.h> #include<conio.h> void main() { clrscr(); int a, b;
  • 17. INTRODUCTION OF C++, DATA TYPES AND 5-17 OPERATORS a = 10; b = 4; a = b; b = 7; cout<<"a:"; cout<<a; cout<<" b:"; cout<<b; getch(); } 4. Increment and decrement operator (++, --). In C++, the increase operator (++) and the decrease operator (--) used to increase or reduce by one the value stored in a variable. They are equivalent to +=1 and to -=1, respectively. Thus: c++; c+=1; c=c+1; The above three statements are all equivalent in its functionality increase by one the value of c. A characteristic of this operator is that it can be used both as a prefix and as a suffix. That means that it can be written either before the variable identifier (++a) or after it (a++). Although in simple expressions like a++ or ++a both have exactly the same meaning. But other expressions in which the result of the increase or decrease operation is evaluated as a value in an outer expression they may have an important difference in their meaning: Notice the difference in table 5.6: Table 5.6 Increase and decrease operator Example 1 Example 2 B=3; A=++B; // A contain 4, B contain 4 B=3; A=B++; // A contain 3, B contain 4 In above table Example 1, B is increased before its value is copied to A. While in Example 2, the value of B is copied to A and then B is increased. 5. Logical operators ( !, &&, || ). The && (AND), || (OR) and | (NOT) operators perform Conditional-AND, Conditional-OR and Conditional-NOT operations on two Boolean expressions. For example: ((5 = = 5)&&(3 > 6))//evaluates to false (true && false) ((5 = = 5)||(3 > 6))//evaluates to true (true || false)
  • 18. 5-18 INTRODUCTION OF C++, DATA TYPES AND OPERATORS 6. Conditional operator (? :). The conditional operator evaluates an expression returning a value if that expression is true and a different one if the expression is evaluated as false. Its format is: condition ? result1 : result2 If condition is true, the expression will return result1, if it is not true it will return result2. The program 5.11 displays the example of conditional operators. Program 5.11. Example of conditional operators #include<iostream.h> #include<conio.h> void main () { clrscr(); int a,b,c; a=2; b=7; c = (a>b) ? a : b; cout << c; getch(); } In this example a is 2 and b is 7, the expression being evaluated (a>b) was not true, thus the first value specified after the question mark was discarded in favor of the second value (the one after the colon) which was b, with a value of 7. 7. Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=,^=, |=). When we want to modify the value of a variable by performing an operation on the value currently stored in that variable we can use compound assignment. The program 5.12 displays the example of assignment operator. Program 5.12. Example of compound assignment operator #include<iostream.h> #include<conio.h> void main() { clrscr(); int a, b=3; a = b; a+=2; // equivalent to a=a+2 cout<<a; getch(); } 8. Bitwise operators ( &, |, ^, ~, <<, >> ). Bitwise operators modify variables considering the bit patterns that represent the values they store as shown in Table 5.7.
  • 19. INTRODUCTION OF C++, DATA TYPES AND 5-19 OPERATORS Table 5.7. Bitwise Operators Operator Equivalent Description & AND Bitwise AND | OR Bitwise Inclusive OR ^ XOR Bitwise Exclusive OR ~ NOT Unary Complement << SHL Shift Left >> SHR Shift Right 9. The size of() operator. This operator accepts one parameter, which can be either a type or a variable itself and returns the size in bytes of that type or object: a = sizeof(char); This will assign the value 1 to a because char is a one-byte long type. The value returned by sizeof is a constant, so it is always determined before program execution. 5.9. EXPRESSIONS IN C++ In C++, anything that evaluates to a value is an expression. An expression is said to return a value. Thus, 3 + 3 returns the value 6 and so is an expression. All expressions are statements. L An expression in C++ is any valid combination of operators, constant and variables. A example of expression in C++: x = a + b; This is an expression not only adds a and b but also assigns the result to x and returns the value of that assignment (the value of x) as well. y = x = a + b; This line is evaluated in the following order: Add a to b. Assign the result of the expression a + b to x. Assign the result of the assignment expression x = a + b to y. If a, b, x, and y are all integers, and if a has the value 2 and b has the value 5, both x and y will be assigned the value 7. The program 5.12 displays the example of expressions.
  • 20. 5-20 INTRODUCTION OF C++, DATA TYPES AND OPERATORS Program 5.13. Example of Expressions #include<iostream.h> #include<conio.h> void main() { clrscr(); int a=0, b=0, x=0, y=35; cout<<"a: "<<a<<" b: "<<b; cout<<" x: "<<x<<" y: "<<y<< endl; a = 9; b = 7; y = x = a+b; cout<<"a: "<<a<<" b: "<<b; cout<<" x: "<<x<<" y: "<<y<< endl; getch(); } POINTS TO REMEMBER (i) C++ is not a pure object oriented language. (ii) Pure object oriented language purely deals with classes objects which means you can not write even very simple program without using a class. If you want to display “Hellow World” you have to write this with in class. (iii) Java is pure object oriented language. (iv) If you want to convert one data type to another data type you have to use type cast. (v) The small individual unit of C++ program is known as a token. (vi) A constant value in C++ is created by using a literal. (vii) Data type specifies the size and type of values that can stored in computer memory. (viii) The range of short integers is from – 32768 to 32767. (ix) Class is user define data type. (x) Operators are special symbols that perform mathematical or logical operation. KEY TERMS ❍ Character set ❍ Identifiers ❍ Basic data type ❍ Integer type ❍ Boolean ❍ Token ❍ Constant ❍ User defined data type ❍ Floating type ❍ Character type
  • 21. INTRODUCTION OF C++, DATA TYPES AND 5-21 OPERATORS ❍ Derived data type ❍ Operator ❍ Increment and decrement ❍ Associativity and precedence ❍ Arithmetical and logical ❍ Assignment operator MULTIPLE CHOICE QUESTIONS 1. A byte can store a relatively small amount of data (a) One single character (b) Double character (c) Integer between 0 and 3267 (d) None of above 2. The smallest integer you can store in a word is declared with the (a) Integer (b) Short keyword (c) Long integer (d) None of above 3. The float is a real number of (a) 2 Byte (c) 8 Byte (b) 4 Byte (d) 16 Byte 4. The double is a real number of (a) 2 Byte (c) 8 Byte (b) 4 Byte (d) 16 Byte 5. To declare a variable as a character use the keyword (a) String (b) Char (c) Character (d) Array 6. The Boolean data type is used to declare a variable whose value would be set as (a) Numeric or character (b) True (1) or False (0) (c) Negative or positive (d) None of above 7. A named location that stores a value is called (a) Variable (b) Character (c) String (d) Function 8. A global variable is a variable declared in the (a) Main body of the source code (b) Inside the main function (c) Inside a class (d) Inside a user function 9. Anything that evaluates a value in C++. (a) Statement (b) Expression (c) Method (d) Operator 10. The symbol used to perform the Boolean operation NOT is. (a) || (b) && (c) ! (d) << >> ⎫ ⎭
  • 22. 5-22 INTRODUCTION OF C++, DATA TYPES AND OPERATORS ANSWERS 1. (a) 6. (b) 2. (b) 7. (a) 3. (b) 8. (a) 4. (c) 9. (b) 5. (b) 10. (c) UNSOLVED QUESTIONS 1. What is C++ ? Explain the features of C++. 2. Explain different token in C++. 3. Write down the structure of C++ program. 4. What do you mean by data type ? Explain different data type in C++. 5. What is the different between user defined and derived data type ? 6. Explain basic data type in C++. 7. What is variable ? Explain the scope of variables in C++. 8. What is operator ? Explain different type of operators in C++. 9. Explain the concept expression in C++. 10. What is the difference between C and C++ ? ❍❍❍