Introduction of C++ By Pawan Thakur

22
INTRODUCTION OF C++, DATA TYPES AND OPERATORS 5-1 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++. 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 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 L

description

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

Transcript of Introduction of C++ By Pawan Thakur

Page 1: Introduction of C++ By Pawan Thakur

INTRODUCTION OF C++, DATA TYPES AND OPERATORS 5-1

5.1. INTRODUCTION OF C++

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

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

5.1.1. Feature of C++. C++ is a superset of the ‘C’ programming language. It containfollowing feature :

1. Object-oriented. The object-oriented features in C++ allow programmers to buildlarge programs with clarity, extensibility and ease of maintenance incorporating the spiritand 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. Classesprovide data hiding, initialization of data, dynamic typing, user controlled memory

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

L

Page 2: Introduction of C++ By Pawan Thakur

5-2 INTRODUCTION OF C++, DATA TYPES AND OPERATORS

management. Classes extend the built-in capabilities of C++ able you in representingand solving complex, real-world problems. A class is an organization of data and functionswhich operate on them. Data structures are called data members and the functions arecalled member functions, the combination of data members and member functionsconstitute a data object or simply an object.

3. Data Abstractions. In C++, classes use the concepts of abstraction and are defineas a list of abstract attributes such as size, height, width, cost and methods that operateon these attributes.

4. Inheritance. The mechanism of deriving a new class form a base class is calledinheritance. C++ support the feature of inheritance. It is the capability of one of the thingto inherit capabilities or properties from another class.

5. Polymorphism. Polymorphism is one of the C++ polymorphism is the concept thatsupports the capability of an object of class to behave differently in response to a messageaction.

6. Portability. C++ and its standard libraries are designed for portability. The currentimplementation will run on most systems that support C. C libraries can be used from aC++ 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 suitablefor 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, operatorsand white space etc.

Character set is valid set of characters. A character set represent anyletter, 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 lexicalelements.

The smallest individual unit of a C++ program is known as a token or alexical unit.

L

L

Page 3: Introduction of C++ By Pawan Thakur

INTRODUCTION OF C++, DATA TYPES AND OPERATORS 5-3

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 tothe language compiler. We cannot use any of the following as identifiers in your programs.

Keywords are the reserved word that have special to the languagecompiler 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.

L

Page 4: Introduction of C++ By Pawan Thakur

5-4 INTRODUCTION OF C++, DATA TYPES AND OPERATORS

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

Some of the example of identifier is as following:

IndiaCon number value4 $my this_is_val

Invalid identifier names include:

2Val number-val Not/right this is my var

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

Constants are data items that never change the value during the executionof 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, 67.567, 456.78, -908.98, 987.23

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.

4. Separators. In C++ there are some characters that are used as separators. ForExample, one of the most important separators in C++ is parentheses, which is used tocontain the list of parameters in functions definition and method invocation. The table5.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 packagesname and classes.

= Equal to sign. Used for variable initializations.

L

L

Page 5: Introduction of C++ By Pawan Thakur

INTRODUCTION OF C++, DATA TYPES AND OPERATORS 5-5

5. Operators. Operators are special symbols that perform mathematical or logicaloperations 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 areevaluated in an expression. The Table 5.3 describes Precedence and Associativity rulesof variable.

Table 5.3 Precedence and Associativity rules for variables

Operator Type Operators Associativity

Postfix Operators x++, x-- Unary postfix increment anddecrement operators associateleft to right, other unary operatorsassociate right to left

Unary prefix operators ++x ,--x ,+x ,-x ~ ,! Right to left

Multiplicative *, / ,% Left to right

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

Conditional AND && Left to right

Conditional OR || Left to right

Conditional ?: Right to left

Assignment = ,+= ,-=, *= ,/= ,%= , Right to left<<= ,>>=, &= ,^= |=

Page 6: Introduction of C++ By Pawan Thakur

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 directivesvoid main () // Main function{

clrscr();cout<<"Hello, world."<<endl; // body of Main functiongetch();

} // End of Main function

Output :

Hello, world.

1. Comment section. The programmer can use comment section for short explanationsof the source code itself or other comment. In above program the comment sectiondisplay the following comment:

// This Program is Written By Pawan Thakur // comment section

2. Preprocessor directive. Lines beginning with a hash sign (#) are directives for thepreprocessor. They are not regular code lines with expressions but indications for thecompiler's preprocessor. For Ex.

#include<iostream.h>

In this case the first directive #include <iostream.h> tells the preprocessor to include theiostream.h standard file.

3. Main function definition. The main function is the point by where all C++ programsstart their execution, independently of its location within the source code. It is essentialthat 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 wordmain 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 compoundexpression that can actually produce some effect. C++ uses curly-braces {} to groupthings together.

cout represents the standard output stream in C++, and the meaning of the entire statementis to insert a sequence of characters into the standard output stream.

Page 7: Introduction of C++ By Pawan Thakur

INTRODUCTION OF C++, DATA TYPES AND OPERATORS 5-7cout<<"Hello, world."<<endl;

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

5.6. DATA TYPES

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

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

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

L

Page 8: Introduction of C++ By Pawan Thakur

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 inC++ are categorized in to numeric and non-numeric. In further, numeric data type are oftwo types:

1. Integer Type2. 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 theshort keyword followed by a name. Because a short integer is signed by default, it canstore a value that ranges from -32768 to 32767. The program 5.1 displays the exampleshort 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 were\n";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. Theprogram 5.2 displays the example integer data type.

Page 9: Introduction of C++ By Pawan Thakur

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 A\n";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 << "\n\tX = " << coordX;cout << "\n\tY = " << coordY;cout << "\n\tZ = " << coordZ;getch();

}

Output-:

(c) Long Integers. An integer variable whose value should be positive can also bedeclared with the long keyword. The long keyword is a positive 32-bit integer whosevalue ranges from 0 to 4,294,967,295. The program 5.3 displays the example integerdata 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";

Page 10: Introduction of C++ By Pawan Thakur

5-10 INTRODUCTION OF C++, DATA TYPES AND OPERATORS

cout << "\n\tArea = " << UArea<< "\n\tPopulation = "<< Population;getch();

}

Output-:

2. Floating - Point. The integers we have used so far have the main limitation of notallowing decimal values. C++ provides floating identifier values that would solve thisproblem. Floating point is another type of integer, used to hold numbers containing decimalparts such as 34.456 and -12.780, 15.89 etc. Float and Double are two types of floatingpoint 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 decimalvalues we can use the float data type. The program 5.4 displays the example of floatdata 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();

}

Page 11: Introduction of C++ By Pawan Thakur

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. Thedouble-precision identifier is an 8 Byte. The program 5.5 displays the example of doubledata 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 functionwhen 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:

Page 12: Introduction of C++ By Pawan Thakur

5-12 INTRODUCTION OF C++, DATA TYPES AND OPERATORS

(a) Character Type. C++ provide char data type, which is used to store charactervalue in computer memory. If the character is of a signed category we declare it as asigned character. This type of variable would be an 8-bit integer whose value can rangefrom – 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 haveonly one value of two possible values, true or false. The program 5.7 displays the exampleof boolean data type.

Program 5.7. Boolean Data Type

#include<iostream.h>#include<conio.h>void main(){

clrscr();

Page 13: Introduction of C++ By Pawan Thakur

INTRODUCTION OF C++, DATA TYPES AND OPERATORS 5-13bool 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 isdefined by user. C++ support following user defined data type :(a) Class. A class is user define data type, a C++ program can have definition ofdifferent classes. A class contains variables and functions. Variables are called instancesand functions are called method. Class is a template, which declare and define methodsthat are called by the objects of the classes.

(b) Structure. A structure is a collection of different types of variables works under onename, providing a convenient means of keeping related information. For example astudent 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 variablesat different times.

(d) Enumeration. An alternative method for naming integer constants is often convenientthen constant. This can be achieved by creating enumeration using keyword enum. Forexample, enum{Start, Pause, Play}.

5.6.4. Derived data type. From the built in data types other data type can be derived byusing 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 fixednumber of values of a single type.

(b) Function. Function is a derived data type. The brief introduction of function is in 6chapter.

(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’smemory in which you can store a value and from which you can later retrieve that value.

Variable represents named storage locations, whose value can bemanipulated 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 asa letter from a to z or from A to Z. Examples are Name, gender, _Students,pRice.

L

Page 14: Introduction of C++ By Pawan Thakur

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 typeint with the identifier a. The second one declares a variable of type float with the identifiermynumber. Once declared, the variables a and mynumber can be used within theirscope 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 typespecifier. We have declared that a, b, and result were of type int, in the previous code atthe 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 thesource 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 ablock. The scope of local variables is limited to the block enclosed in braces {} where

Page 15: Introduction of C++ By Pawan Thakur

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 afunction 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 arerepresented by operators.

Operators are special symbols that perform mathematical or logicaloperations 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 supportedby 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 themathematical operators.

L

Page 16: Introduction of C++ By Pawan Thakur

5-16 INTRODUCTION OF C++, DATA TYPES AND OPERATORS

2. Relational operators and equality. The equality and relational operators are usedif one operand is greater than, less than, equal to or not equal to another operand. TheTable 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 valuesare 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 displaysthe example of assignment operator.

Program 5.10. Example of assignment operator

#include<iostream.h>#include<conio.h>void main(){

clrscr();int a, b;

Page 17: Introduction of C++ By Pawan Thakur

INTRODUCTION OF C++, DATA TYPES AND OPERATORS 5-17a = 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 avariable. 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 thevalue 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 samemeaning. But other expressions in which the result of the increase or decrease operationis evaluated as a value in an outer expression they may have an important difference intheir meaning: Notice the difference in table 5.6:

Table 5.6 Increase and decrease operator

Example 1 Example 2

B=3; B=3;A=++B; A=B++;

// A contain 4, B contain 4 // A contain 3, B contain 4

In above table Example 1, B is increased before its value is copied to A. While inExample 2, the value of B is copied to A and then B is increased.

5. Logical operators ( !, &&, || ). The && (AND), || (OR) and | (NOT) operatorsperform Conditional-AND, Conditional-OR and Conditional-NOT operations on twoBoolean expressions. For example:

((5 = = 5)&&(3 > 6))//evaluates to false (true && false)((5 = = 5)||(3 > 6))//evaluates to true (true || false)

Page 18: Introduction of C++ By Pawan Thakur

5-18 INTRODUCTION OF C++, DATA TYPES AND OPERATORS

6. Conditional operator (? :). The conditional operator evaluates an expression returninga value if that expression is true and a different one if the expression is evaluated asfalse. Its format is:

condition ? result1 : result2

If condition is true, the expression will return result1, if it is not true it will returnresult2. 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, thusthe first value specified after the question mark was discarded in favor of the secondvalue (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 valuecurrently stored in that variable we can use compound assignment. The program 5.12displays 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+2cout<<a;getch();

}

8. Bitwise operators ( &, |, ^, ~, <<, >> ). Bitwise operators modify variablesconsidering the bit patterns that represent the values they store as shown in Table 5.7.

Page 19: Introduction of C++ By Pawan Thakur

INTRODUCTION OF C++, DATA TYPES AND OPERATORS 5-19

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 atype 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 returnedby 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 toreturn a value. Thus, 3 + 3 returns the value 6 and so is an expression. All expressionsare statements.

An expression in C++ is any valid combination of operators, constantand 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 thevalue 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 expressiona + b to x. Assign the result of the assignment expression x = a + b to y. If a, b, x, and yare all integers, and if a has the value 2 and b has the value 5, both x and y will beassigned the value 7. The program 5.12 displays the example of expressions.

L

Page 20: Introduction of C++ By Pawan Thakur

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 youcan not write even very simple program without using a class. If you want todisplay “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 typecast.

(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 computermemory.

(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 ❍ Token❍ Identifiers ❍ Constant❍ Basic data type ❍ User defined data type❍ Integer type ❍ Floating type❍ Boolean ❍ Character type

Page 21: Introduction of C++ By Pawan Thakur

INTRODUCTION OF C++, DATA TYPES AND OPERATORS 5-21

❍ Derived data type ❍ Associativity and precedence❍ Operator ❍ Arithmetical and logical❍ Increment and decrement ❍ Assignment operator

MULTIPLE CHOICE QUESTIONS1. 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 (b) 4 Byte(c) 8 Byte (d) 16 Byte

4. The double is a real number of(a) 2 Byte (b) 4 Byte(c) 8 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 setas(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) << >>

Page 22: Introduction of C++ By Pawan Thakur

5-22 INTRODUCTION OF C++, DATA TYPES AND OPERATORS

ANSWERS1. (a) 2. (b) 3. (b) 4. (c) 5. (b)6. (b) 7. (a) 8. (a) 9. (b) 10. (c)

UNSOLVED QUESTIONS1. 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++ ?

❍ ❍ ❍