chapter 2 · pdf file// c++ program to illustrate ... this makes programs easier to write and...

68
www.sahajsolns.com Chapter 2 Chapter 2

Upload: nguyenhanh

Post on 21-Mar-2018

220 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Chapter 2Chapter 2

Page 2: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Topic Contents� The IO Stream class

� C++ Comments

� C++ Keywords

Variable Declaration� Variable Declaration

� The const Qualifier

� The endl, setw, setprecision, manipulators

� The scope resolution operator

� The new & delete operator

OOPS with C++ Sahaj Computer Solutions 2

Page 3: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

What is C++?� C++ is an object oriented programming language.

� It was developed by Bjarne Stroupstrup at AT&T Bell Laboratories in Murray Hills, New Jersey USA in 1979

� Initially it was called as ‘C with Classes’� Initially it was called as ‘C with Classes’

� However later in 1983 , the name was changed to C++.

� The idea of C++ comes from the C increment operator ++, thereby suggesting that C++ is augmented (incremented) version of C.

OOPS with C++ Sahaj Computer Solutions 3

Page 4: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

What is C++?� C++ is superset of C. Most of what we already know

about C applies to C++ also.

C++

OOPS with C++ Sahaj Computer Solutions 4

C++

InheriatanceClassesFunction

&Operator Overloading

C

Page 5: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Applications of C++� C++ allows us to create a hierarchical related objects,

and object libraries.

� C++ will map the real world problem properly as well as it has the ability to get close to C part of middle as it has the ability to get close to C part of middle level details.

� C++ programs are easily maintainable and expandable.

� It is expected that C++ will replace C as a general purpose language in the near future.

OOPS with C++ Sahaj Computer Solutions 5

Page 6: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Comments� C++ introduces a new comment symbol // (double

slash).

� Comments start with double slash symbol and terminate at the end of the line.terminate at the end of the line.

� The comment may start anywhere in the line and whatever follows till the end of line is ignored.

� Note that there is no closing symbol

� The // comments is basically a single line comment

� The C comment symbol (/* */) is still valid and are known as multi line comments.

OOPS with C++ Sahaj Computer Solutions 6

Page 7: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Comments� Single Line Comments

// This is an example of

// C++ Program to illustrate

// Comments// Comments

� Multi Line Comments

/* This is an example of

C++ program to demonstrate

Multiline Comments */

OOPS with C++ Sahaj Computer Solutions 7

Page 8: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Keywords� The keywords implement specific C++ language

features and cannot be explicitly used as names for the program variables , functions, classes, structures or functions. functions.

� Following are the keywords used in C++

OOPS with C++ Sahaj Computer Solutions 8

asm auto break case catch operator private

char class const continue default protected public

delete do double else enum register return

extern float for friend goto short signed

if inline int long new sizeof static

struct switch template this throw try typedef

Page 9: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Keywordsunion unsigned virtual void volatile while

bool const_cast dynamic_cast explicit Export

Added by Ansi C++

OOPS with C++ Sahaj Computer Solutions 9

bool const_cast dynamic_cast explicit Export

false mutable namespace reinterpret_cast

static_cast

true typeid typename using wchar_t

Page 10: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Identifiers and Constants� Identifiers refer to the name of variables, functions,

arrays, classes, etc created by the programmers.

� Rules:

� Only alphabetic characters, digits and underscore are � Only alphabetic characters, digits and underscore are permitted

� The name cannot start with a digit.

� Uppercase and Lowercase letters are distinct

� Keywords cannot be used as variable name.

� Constants refer to fixed values that do not change during the execution of a program.

OOPS with C++ Sahaj Computer Solutions 10

Page 11: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Program structure� C++ program would

contain four sections.� The class declarations

contains class definition with function declaration

Header Files

with function declaration� Member function

definitions contains the definition of functions with a scope resolution operator which represents its class.

� Main Function is the start point of any c++ program

OOPS with C++ Sahaj Computer Solutions 11

Class Declaration

Member Function definitions

Main Function Program

Page 12: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

First C++ Program// A simple C++ Program

#include<iostream.h>

int main()

{{

cout<<“C++ is better than C.\n”; // C++ statement

return 0;

} //end of program

OOPS with C++ Sahaj Computer Solutions 12

Page 13: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

The iostream File� # include<iostream.h>

� This directive causes the preprocessor to ass the contents of iostream file to the program.

� It contains declarations for cout and the operator <<.� It contains declarations for cout and the operator <<.

� It should be included at the beginning of all programs that use input/output.

OOPS with C++ Sahaj Computer Solutions 13

Page 14: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Output Operator� C++ introduces two new features cout and <<.

� The identifier cout (pronounced as C out) is a predefined object that represents the standard output stream in c++.stream in c++.

� Here the standard output stream represents the screen.

� The cout has a simple interface. If string represents a string variable , then the following statement will display its content.

cout<< string;

OOPS with C++ Sahaj Computer Solutions 14

Page 15: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Output Operator� The operator << represents the bitwise left shift

operator and is known as Insertion operator.

� Example:

cout<<“This is my first c++ program”;cout<<“This is my first c++ program”;

� Will display the string This is my first c++ program on the standard output device (screen).

OOPS with C++ Sahaj Computer Solutions 15

C++ << “This is my first c++ program”

Object VariableInsertion Operator

Page 16: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Return type of main()� In C++ main() returns an integral type value to the

operating system.

� Therefore every main() in C++ should end with a return(0) statement; otherwise the compiler will return(0) statement; otherwise the compiler will throw and warning .

� The default return type of main function is int.

OOPS with C++ Sahaj Computer Solutions 16

Page 17: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Input Operator� The statement

cin>>number1;

is an input statement and causes the program to wait for the users to type in a number . The number keyed is placed in the variable number1.in the variable number1.

� The operator >> is known as extraction or get from operator .

� It extracts the value from the keyboard and assigns it to the variable to the right

OOPS with C++ Sahaj Computer Solutions 17

cin 45.5>>

Object VariableExtraction Operator

Page 18: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Basic Data TypesC++ Data Types

User Defined type

Structure

Derived type

Array

Built-in type

OOPS with C++ Sahaj Computer Solutions 18

StructureUnionClass

enumeration

ArrayFunctionPointer

reference

Integral type void Floating type

int char float double

Page 19: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

DatatypesType Bytes Range

char 1 -128 to 127

unsigned char 1 0 to 255

signed char 1 -128 to 127

int 2 -32768 to 32767

unsigned int 2 -32768 to 32767unsigned int 2 -32768 to 32767

signed int 2 0 to 65535

short int 2 -32768 to 32767

unsigned short int 2 0 to 65535

signed short int 4 -32768 to 32767

long int 4 -2147483648 to 21474836487

signed long int 4 -2147483648 to 21474836487

float 4 0 to 4294967295

double 8 1.7E-38 to 1.7E+308

long double 8 3.4-4932 to 1.1E+4932OOPS with C++ Sahaj Computer Solutions 19

Page 20: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Another C++ Program#include<iostream.h>int main(){

int number1,number2,sum;float average;float average;cout<<“Enter two numbers”<<endl;cin>>number1>>number2;sum=number1+number;average=sum/2;cout<<“Average:”<<average;return(0);

}

OOPS with C++ Sahaj Computer Solutions 20

Page 21: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

User defined Data Types� Structures and Classes

� C has user defined data types such as struct and union

� These data types are legal in C++ and some more new features have been added to make them suitable for the features have been added to make them suitable for the object orientation programming

� C++ permits another user-defined data type known as class which can be used , just like any other basic data type, to declare variables.

� The class variables are known as objects, which are central focus of object orientated programming

OOPS with C++ Sahaj Computer Solutions 21

Page 22: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Enumerated Data Type� An enumerated data type is another user-defined data

type which provides a way for attaching names to numbers.

� In other words enumeration data type is used for � In other words enumeration data type is used for creating symbolic constants.

� The enum keywords automatically enumerates a list of words by assigning them values 0,1,2,3 and so on.

� Example:

enum shape{circle,square,triangle};

enum color{red,blue, green,yellow};

OOPS with C++ Sahaj Computer Solutions 22

Page 23: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Enumerated data type� In C++ the tag name shape, color becomes new type

names.

� By using the tag names we can declare variables.

Example:Example:

shape ellipse; //ellipse is of type shape

� By default enumerators are assigned integer vales starting with 0 for the first enumerator, 1 for the second enumerator and so on.

� We can override the default values by explicitly assigning integers to enumerators

OOPS with C++ Sahaj Computer Solutions 23

Page 24: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Enumerated data type� Example:

enum color{red,blue=6,green=9};

enum color{red=5,blue,green}

In the first case , red is 0 by default, blue is 6 and � In the first case , red is 0 by default, blue is 6 and green is 9.

OOPS with C++ Sahaj Computer Solutions 24

Page 25: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Example Programenum shape{

circle,rectangle,triangle

};

case circle: cout<<“ Shape is Circle”<<endl;break;

case rectangle:cout<<“ Shape is Rectangle”<<

endl;

OOPS with C++ Sahaj Computer Solutions 25

};void main(){

cout<<“Enter shape code:”;int code;cin>> code;while(code>=circle && code<=triangle){

switch(code)

endl;break;

case triangle:cout<<“ Shape is Triangle”<<endl;break;

default:cout<<“Invalid Code”<<endl;break;

}break;}

Page 26: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Declaration of Variables� We know that in C, all the variable s must be declared

before they are used.

� This is true with C++ as well.

� However there is a significant difference in C++ with � However there is a significant difference in C++ with regard to place of declaration in the program.

� C requires all the variables to be defined at the beginning of the program.

� Before using the variable we need to go the beginning of the program to see whether it has been declared and if so , of what type

OOPS with C++ Sahaj Computer Solutions 26

Page 27: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Declaration of Variables� C++ allows us to declare a variable anywhere in the

scope.

� This means that the variable can be declared right at the place of its first use.the place of its first use.

� This makes programs easier to write and reduces errors that may be caused by having to scan back and forth.

� It also makes program easier to understand because the variables are declared in the context of their first use.

� Program : ch2pg4.cpp

OOPS with C++ Sahaj Computer Solutions 27

Page 28: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Reference Variables� C++ introduces a new kind of variable known as the

reference variable.� A reference variable provides an alias (alternative name )

for the previously defined variable� For example, if we make the variable sum a reference to the � For example, if we make the variable sum a reference to the

variable total then sum and total can be used interchangeably to represent that variable.

� A reference variable can be created as follows:data-type & reference-name = variable-name

� Examplesfloat total=100;float & sum =total;

OOPS with C++ Sahaj Computer Solutions 28

Page 29: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Reference Variables� Both the variables now refer to the same data object in

the memory. Now the statement

cout<<total;

And And

cout<<sum;

� Both prints the value 100.

� A reference variable must be initialized at the time of declaration.

OOPS with C++ Sahaj Computer Solutions 29

Page 30: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Operators in C++C++ Operators

Unary Operators Binary Operators TernaryOperators

OOPS with C++ Sahaj Computer Solutions 30

Increment Op++

Decrement Op--

Conditional Operator

? :

Arithmetic Operators

RelationalOperators

Bitwise OperatorsBoolean

Operators

Page 31: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Operators in C++� Arithmetic Operators

Operator Operation Syntax Example

+ Addition Result=op1+op2 Sum=5+6

_ Subtraction Result=op1-op2 Diff=a-3

OOPS with C++ Sahaj Computer Solutions 31

_ Subtraction Result=op1-op2 Diff=a-3

* Multiplication Result=op1*op2 Mul=5*2

/ Division Result=op1/op2 Div=sum/2

% Modulo Division Result=op1%op2 Rem=n%2

Program ch2pg7.cpp

Page 32: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Relational Operators� In the term relational operator, relational refers to the

relationships that values can have with one another.

� Some of the C++ relational operators are

Operator Operation Syntax Example

OOPS with C++ Sahaj Computer Solutions 32

Operator Operation Syntax Example

< Less than Op1<Op2 If(9<2) result=9;

> Greater than Op1>Op2 If(a>1) result=“a is large”

<= Less than or equal Op1<=Op2 If(a<=b) result=b;

>= Greater than or equal Op1>=Op2 If(z>=y) z++;

== Equal Op1==Op2 If(num1==num2) s=0;

!= Not equal Op1!=Op2 If(a!=b) cout<<“not equal”;

Page 33: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Logical Operators� Logical operator provides a way of connecting two or

more expressions.

Operators Actions Syntax

OOPS with C++ Sahaj Computer Solutions 33

Operators Actions Syntax

&& AND Expr1 && Expr2

|| OR Expr1 ||Expr2

! NOT ! Expr

Page 34: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Logical Operators

P Q P &&Q P||Q !P

0 0 0 0 1

TRUTH TABLE

0 1 0 1 1

1 0 0 1 0

1 1 1 1 0

OOPS with C++ Sahaj Computer Solutions 34

Program: ch2pg8.cpp

Page 35: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Bitwise Operators� Bitwise operation refers to testing, setting, or shifting

the actual bits in a byte or word, which correspond to the char and int data types and variants.

� You cannot use bitwise operations on float, double, � You cannot use bitwise operations on float, double, long double, void, bool, or other, more complex types.

� Bitwise operations are applied to the individual bits of the operands.

OOPS with C++ Sahaj Computer Solutions 35

Page 36: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Bitwise OperatorsOperator Action

& AND

| OR

^ Exclusive OR (XOR)

~ One’s Compliment(NOT)

<< Right Shift

>> Left Shift

OOPS with C++ Sahaj Computer Solutions 36

Program: ch2pg10.cpp

Page 37: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Bitwise Operators� The bit-shift operators, >> and <<, move all bits in a

variable to the right or left as specified.

� The general form of the shift-right statement is

variable >> number of bit positionsvariable >> number of bit positions

� The general form of the shift-left statement is

variable << number of bit positions

� As bits are shifted off one end, 0's are brought in the other end.

� Program: ch2pg9.cpp

OOPS with C++ Sahaj Computer Solutions 37

Page 38: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Conditional Operator� The ternary operator ? takes the general form

Exp1 ? Exp2 : Exp3;

� where Exp1, Exp2, and Exp3 are expressions.

� The ? operator works like this: Exp1 is evaluated.� The ? operator works like this: Exp1 is evaluated.

� If it is true, Exp2 is evaluated and becomes the value of the expression.

� If Exp1 is false, Exp3 is evaluated and its value becomes the value of the expression. For example, in

x = 10;

y = x>9 ? 100 : 200;

� y is assigned the value 100.

OOPS with C++ Sahaj Computer Solutions 38

Page 39: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Increment and Decrement� C++ includes two useful operators not generally found in other

computer languages.

� These are the increment and decrement operators, ++ and −−.

� The operator ++ adds 1 to its operand, and −− subtracts one. In other words:other words:

x = x+1;

� is the same as

++x;

� And

x = x-1;

� is the same as

x--;

OOPS with C++ Sahaj Computer Solutions 39

Page 40: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Increment and Decrement� Both the increment and decrement operators may

either precede (prefix) or follow (postfix) the operand. For example,

x = x+1;x = x+1;

� can be written

++x;

or

x++;

OOPS with C++ Sahaj Computer Solutions 40

Program : ch2pg11.cpp

Page 41: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Control Structures� The general form of the if statement is

if (expression) statement;

else statement;

� Example:

if(age<=18)

cout<<“ Not Eligible to Vote”

else

cout<<“Eligible to Vote”;

OOPS with C++ Sahaj Computer Solutions 41

Program : CH2PG12.cpp

Page 42: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Control Structures� Nested ifs : if inside another if is called nested if

� Syntax:if(expression)

{

if(expression2)if(expression2)

statement1;

else

statement2

}

else

statement3;

OOPS with C++ Sahaj Computer Solutions 42

Program :CH2PG3.CPP

Page 43: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Switch Statement� A switch statement is a multi branching statement where ,

based on a condition , the control is transferred to one of many possible points.

� Syntax:

switch(expression)switch(expression)

{

case 1: action;

case 2: action;

:

default: action;

};

OOPS with C++ Sahaj Computer Solutions 43

Page 44: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Switch Statement� There are three important things to know about the

switch statement:� The switch differs from the if in that switch can only test

for equality, whereas if can evaluate any type ofrelational or logical expression.relational or logical expression.

� No two case constants in the same switch can haveidentical values. Of course, a switch statement enclosedby an outer switch may have case constants that are thesame.

� If character constants are used in the switch statement,they are automatically converted to integers.

OOPS with C++ Sahaj Computer Solutions 44

Page 45: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Switch Case Exampleswitch(i) {

case 1: /* These cases have common */case 2: /* statement sequences. */case 3:

flag = 0;break;break;

case 4:flag = 1;

case 5:error(flag);break;

default:process(i);

}

OOPS with C++ Sahaj Computer Solutions 45

Page 46: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Iteration Statements� In C/C++, and all other modern programming

languages, iteration statements (also called loops)allow a set of instructions to be executed repeatedlyuntil a certain condition is reached.until a certain condition is reached.

� This condition may be predefined (as in the forloop), or open-ended (as in the while and do-whileloops).

OOPS with C++ Sahaj Computer Solutions 46

Page 47: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

The for Loop� The general form of the for statement is:

for(initialization; condition; increment) {

statement;statement;

}

� Example:

for(x=1; x <= 100; x++)

cout<< x;

OOPS with C++ Sahaj Computer Solutions 47

Program : CH2PG14.CPP

Page 48: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

The while Loop� Its general form is

while(condition) statement;

� where statement is either an empty statement, a single statement, or a block of statements. statement, or a block of statements.

� The condition may be any expression, and true is any nonzero value.

� The loop iterates while the condition is true.

� When the condition becomes false, program control passes to the line of code immediately following the loop.

OOPS with C++ Sahaj Computer Solutions 48

Page 49: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

The While Loop� Example:

while(ch != 'A') ch = getchar();

return ch;

� Program: CH2PG15.CPP

OOPS with C++ Sahaj Computer Solutions 49

Page 50: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

The do-while Loop� Unlike for and while loops, which test the loop

condition at the top of the loop, the do-while loop checks its condition at the bottom of the loop.

� This means that a do-while loop always executes at � This means that a do-while loop always executes at least once.

� The general form of the do-while loop is

do{

statement;

} while(condition);

OOPS with C++ Sahaj Computer Solutions 50

Page 51: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

The do-while Loop� Example:

do {

scanf("%d", &num);

} while(num > 100);

� Program: CH2PG16.cpp

OOPS with C++ Sahaj Computer Solutions 51

Page 52: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Jump Statements� C/C++ has four statements that perform an

unconditional branch: return, goto, break, and continue.

� Of these, you may use return and goto anywhere in � Of these, you may use return and goto anywhere in your program.

� You may use the break and continue statements in conjunction with any of the loop statements.

OOPS with C++ Sahaj Computer Solutions 52

Page 53: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

The return Statement� The return statement is used to return from a function.

� It is categorized as a jump statement because it causes execution to return (jump back) to the point at which the call to the function was made.the call to the function was made.

� A return may or may not have a value associated with it.

� The general form of the return statement is

return expression;

OOPS with C++ Sahaj Computer Solutions 53

Page 54: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

The goto Statement� The general form of the goto statement is

goto label;

..

.

label:

� where label is any valid label either before or after goto.

OOPS with C++ Sahaj Computer Solutions 54

Page 55: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

The goto Statement� For Example:

x = 1;

loop1:

x++;

if(x<100) goto loop1;

OOPS with C++ Sahaj Computer Solutions 55

Page 56: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

The break Statement� The break statement has two uses. You can use it to

terminate a case in the switch statement.

� You can also use it to force immediate termination of a loop, bypassing the normal loop conditional test.loop, bypassing the normal loop conditional test.

� When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.

� Program: CH2PG16.CPP

OOPS with C++ Sahaj Computer Solutions 56

Page 57: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

The continue Statement� The continue statement works somewhat like the

break statement.

� Instead of forcing termination, however, continue forces the next iteration of the loop to take place, forces the next iteration of the loop to take place, skipping any code in between.

� Program: CH2PG17.CPP

OOPS with C++ Sahaj Computer Solutions 57

Page 58: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Arrays� An array is a collection of variables of the same type

that are referred to through a common name.

� A specific element in an array is accessed by an index.

� The general form for declaring a array is� The general form for declaring a array is

type var_name[size];

� Example:

double balance[100];

� Program : CH2PG18.cpp

OOPS with C++ Sahaj Computer Solutions 58

Page 59: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Pointers� A pointer is a variable that holds a memory address.

� This address is the location of another object (typically another variable) in memory.

� For example, if one variable contains the address of another variable, the first variable is said to point to the

Program: CH2PG19.cpp

For example, if one variable contains the address of another variable, the first variable is said to point to the second.

� The general form for declaring a pointer variable is

type *name;� where type is the base type of the pointer and may be any valid

type.

� The name of the pointer variable is specified by name.

OOPS with C++ Sahaj Computer Solutions 59

Page 60: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Const Qualifier� The const modifier is used for creating symbolic constant

in C++.

� Any value declared as const cannot be modified by the program in any way.

In C++ we can use const in a constant expression such as � In C++ we can use const in a constant expression such as const int size=10;

char name[size];

� As with long and short if we use the const modifier alone , it defaults to int. For example

const size =10 ; means

const int size=10;

OOPS with C++ Sahaj Computer Solutions 60

Page 61: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Manipulators� Manipulators are operators that are used to format the

data display.

� The most commonly used manipulators are endl and setw.setw.

� The endl manipulator , when used in an output statement causes a line feed to be inserted.

� It has same effect as using the new line character ‘\n’.

� Example:

cout<<endl;

OOPS with C++ Sahaj Computer Solutions 61

Page 62: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Manipulator� setw(w) : Set the field width to w.

For example: cout<<setw(5)<<sum<<endl;

� setprecision() : Set the number of digits of precision.

For example: cout<<setprecision(6)<<num;For example: cout<<setprecision(6)<<num;

� setfill(int ch) : Set the fill character to ch.Example: cout<<setfill(‘*’);

� flush : Flush a stream.

� To access manipulators that take parameters (such as setw() ), you must include <iomanip> in your program.

OOPS with C++ Sahaj Computer Solutions 62

Page 63: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Scope Resolution Operator� C++ is also block structured language, this means

blocks and scope can be used in constructing programs.

� A scope of the variable extends from the point of its � A scope of the variable extends from the point of its declaration till the end of the block containing the declaration.

� A variable declared inside that block is said to be local to that block .

� Consider the following example:

OOPS with C++ Sahaj Computer Solutions 63

Page 64: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Scope Resolution::::::::::::::::::::::::

{

int x=100;

:::::::::::::::::::::::::::

� The two declarations of x refers to 2 different memory locations containing different values. :::::::::::::::::::::::::::

}

::::::::::::::::::::::

{

int x=1;

:::::::::::::::::::::::::::::;

}

values.

� Statements in second block cannot refer to the variable x declared in first block and vice versa.

� Blocks in C++ are often nested.

OOPS with C++ Sahaj Computer Solutions 64

Page 65: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Scope Resolution:::::::::::::::::::::

{// Block 1

int x=10;

::::::::::::::::::::

� Block2 is contained in block1.

� The declaration in inner block hides a declaration of the same variable in

::::::::::::::::::::

{ //Block 2

int x=1;

::::::::::::

}

::::::::::::::::::::::::::::::

}

block hides a declaration of the same variable in an outer block and therefore each declaration of x causes it to refer to a different data object.

OOPS with C++ Sahaj Computer Solutions 65

Page 66: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Scope Resolution Operator� The global version of variable cannot be accessed from

within the inner block.

� C++ resolves this problem by introducing a new operator :: called scope resolution operator.operator :: called scope resolution operator.

� This can be used to uncover a hidden variable.

� It takes the following form:

:: variable-name;

� For Example:

cout<<::m

OOPS with C++ Sahaj Computer Solutions 66

Program: CH2PG21.cpp

Page 67: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Memory Management Operators� C++ has two unary operators new and delete that perform

the task of allocating and freeing the memory better and easier way.

� The new operator can be used to create objects of any type.� The new operator can be used to create objects of any type.

� It takes the following general form:

pointer-variable =new data-type;

� When the data is no longer needed, it is destroyed to release the memory space for reuse.

� The general form of its use is:

delete pointer-variable;

OOPS with C++ Sahaj Computer Solutions 67

Page 68: Chapter 2 · PDF file// C++ Program to illustrate ... This makes programs easier to write and reduces errors ... Operators in C++ Arithmetic Operators Operator Operation Syntax Example

www.sahajsolns.com

Sahaj Computer Solutions Near Gomatesh School, Hindwadi Belgaum-11, Phone no: 4200864,2481703

Get Certified in

•Microsoft Office 2010•Tally 9.2•.NET 2008•J2EE•CORE JAVA

� Around 1800 students developed software projects and scored the top scores in exams.

� One stop shop for •CORE JAVA•C PROGRAMMING•OOPS WITH C++•JOOMLA•WORDPRESS•PHP AND MYSQL•SQLSERVER•UNIX AND LINUX•ANDRIOD APPS

� One stop shop for � Software Projects

� Website Development

� Technology Training

� I.T Research Visit: www.sahajsolns.com

OOPS with C++ Sahaj Computer Solutions 68