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

C++ Progrmming Unit I

Uploaded by

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

C++ Progrmming Unit I

Uploaded by

Big Bro
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

BCA – IstYr

Programming in C++

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 1 of 24


Unit – I

Object Oriented Paradigm:


The Object Oriented Paradigm is the latest in the software development and the most adopted one in the
developing projects of today. The paradigm means organizing principle of a program. It is an approach to
programming. Since the invention of the computer, many programming approaches have been tried such as
procedural programming, modular programming, structural programming etc.

The object-oriented programming is a method of implementation in which programs are organized as


cooperative collections of objects, each of which represents an instance of some class, and whose classes are
all members of a hierarchy of classes united via inheritance relationship. OOP uses objects as its
fundamental building blocks. Each object is an instance of some class. Classes allow the mechanism of data
abstraction for creating new data types. Inheritance allows building of new classes from the existing classes.
Hence, if any of these elements are missing in a program, then it is not object-oriented one; it resembles the
program with abstract data types.

The Basic concepts of OOPs

(a) Object: Object is the basic unit of object-oriented programming. Objects are identified by its
unique name. An object represents a particular instance of a class. There can be more than one
instance of an object. An object is an identifiable entity with some characteristics and behavior. It
represents an entity that can store data and its associated functions.

For instance, ‘Orange’ is an object. Its characteristics are: it is spherical shaped, its colour is orange
etc. Its behavior is: it is juicy and its tastes sweet-sour.

(b) Class: A class is a group of objects that share common properties and relationships. It
represents a group of similar objects.

Thus a Class represents a set of individual objects. Characteristics of an object are represented in a
class as Properties. The actions that can be performed by objects become functions of the class and is
referred to as Methods.

For example, consider a Class of Cars under which Santro Xing, Alto and WaganR represent
individual Objects. In this context each Car Object will have its own, Model, Year of Manufacture,
Colour, Top Speed, Engine Power etc., which form Properties of the Car class and the associated
actions i.e., object functions like Start, Move, Stop form the Methods of Car Class.

No memory is allocated when a class is created. Memory is allocated only when an object is created,
i.e., when an instance of a class is created.

(c) Data Abstraction: Abstraction refers to the act of representing essential features without
including the background details or explanation between them.

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 2 of 24


For example, a class Car would be made up of an Engine, Gearbox, Steering, and many more
components. To build the Car class, one does not need to know how the different components work
internally, but only how to interface with them.

(d) Data Encapsulation: Encapsulation is the most fundamental concept of OOP. It is the way
of combining both data and the functions that operate on that data under a single unit.

The wrapping up of data and functions (that operate on the data) into a single unit (called class) is
known as Encapsulation.
When using Data Encapsulation, data is not accessed directly, it is only accessible through the
functions present inside the class. These functions are called member functions in C++.

For example, in a company, departments access and work with their data on their own. One
department cannot access data of other department directly. Rather a request is made for the required
data and the data is handed over by the members of the requested department. Thus, it can be said
that department data and department employees are encapsulated into a single entity, the department.

(e) Inheritance: Inheritance is the capability of one class of things to inherit capabilities or
properties from another class.

The class, whose properties are inherited, is called Base Class or Super Class and the class that
inherits these properties, is called Derived Class or Sub Class.

Inheritance helps in reducing the overall code size of the program, which is an important concept in
object-oriented programming.

It is classifieds into different types, they are

• Single level inheritance


• Multi-level inheritance
• Hybrid inheritance
• Hierarchical inheritance
• Multiple inheritance

(f) Polymorphism: Polymorphism is the ability for a message or data to be processed in more than
one form. Polymorphism is a property by which the same message can be sent to objects of several
different classes.

The word Polymorphism is derived from two Greek words Poly which means many and morphos
which means forms. C++ provides three different types of polymorphism:

o Virtual Function
o Function Overloading
o Operator Overloading

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 3 of 24


(g) Binding: Binding refers to the process that is used to convert identifiers into machine language
addresses. There are two types of bindings:
• Early binding or static binding: Early binding means the compiler is able to directly
associate the identifier name (such as a function or variable name) with a machine address. In
other words, binding is performed at compile time.
• Late binding or dynamic binding: Dynamic binding refers to the case where compiler is
not able to resolve the call and the binding is done at runtime only.

(h) Message Passing: The process by which an object sends data to another object or asks the other
object to invoke a method is known as message passing. It is also known as interfacing.

Applications of OOP:
The main application areas of OOP are

• Real Time Systems


• User Interface design such as Windows, Menu, etc.
• Object Oriented Databases
• Simulation and Modeling
• Artificial Intelligence and Expert System
• Neural Networks and Parallel Processing
• Decision Support and Office Automation system

Advantages of OOP:
The main advantages of OOP are

• It is easy to model a real system as real objects are represented by programming objects in OOP.
• With OOP, programs are easy to understand.
• OOP offers classes reusability. Already created classes can be reused without having to write them
again. This saves time and cost of program.
• With OOP, programs are easier to test, manage and maintain.
• It helps to manage software complexity easily.
• OOP facilitates Quick Development as parallel development of classes is possible.

Disadvantages of OOP:
Although OOP has proved revolutionary in software development yet it has some disadvantages too. These
are

• With OOP, classes tend be overly generalized.

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 4 of 24


• The relations among classes become artificial at times.
• The OOP programs design is tricky.
• One needs to do proper planning and proper design for OOP programming.
• To program with OOP, programmer need proper skills such as design skills, programming skills,
thinking in terms of objects etc.

Difference between Procedure Oriented Programming (POP) & Object Oriented


Programming (OOP)

S.No. Procedure Oriented Programming Object Oriented Programming


In POP, program is divided into small parts
1 In OOP, program is divided into parts called objects.
called functions.
In POP, importance is not given to data but to In OOP, importance is given to the data rather than
2 functions as well as sequence of actions to be procedures or functions because it works as a real
done. world.
3 POP follows Top Down approach. OOP follows Bottom Up approach.
OOP has access specifiers named Public, Private,
4 POP does not have any access specifier.
Protected, etc.
In POP, Data can move freely from function to In OOP, objects can move and communicate with
5
function in the system. each other through member functions.
To add new data and function in POP is not so OOP provides an easy way to add new data and
6
easy. function.
In POP, Most function uses Global data for In OOP, data can not move easily from function to
7 sharing that can be accessed freely from function function,it can be kept public or private so we can
to function in the system. control the access of data.
POP does not have any proper way for hiding OOP provides Data Hiding so provides more
8
data so it is less secure. security.
In OOP, overloading is possible in the form of
9 In POP, Overloading is not possible.
Function Overloading and Operator Overloading.
Examples of POP are: C, VB, FORTRAN, Examples of OOP are: C++, JAVA, VB.NET,
10
PASCAL. C#.NET.

C++ Character Set: Character set is a set of valid characters that a language can recognize. A
character represents any letter, digit, or any other sign. The C++ has the following character set
Letters A-Z, a-z
Digits 0–9
Special Symbols + - / ( ) [ ] { } = < > & ^ % * # @ <= >=
White Space Blank Space, Horizontal tab (→), new line
Other Character C++ can process any of the 256 ASCII characters as data or as literals.

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 5 of 24


Tokens:
The smallest individual unit in a program is known as a Token. They are the basic building blocks of a C++
program. Tokens are useful for compiler to detect errors. When tokens are not arranged in a particular
sequence, the compiler generates an error message.
C++ has the following tokens:

• Keywords
• Identifiers
• Constants (Literals)
• Punctuators
• Operators

Keywords:
Keywords are the words that convey a special meaning to the language compiler. These are reserved for
special purpose and must not be used as normal identifier names.
C++ supports 64 keywords. Few of them are as follows:

do for if else int float


double char struct union long case
break while goto short auto void

Constants (Literals):
Constants are the data items that never change their value during a program. Every constant used in a C++
program has a type that is determined by its form and a value. Its value is set when the program is written,
and it retains this value throughout the program’s existence.

C++ language has the following types of constants:

• Integer constants
• Character constants
• Floating point constants
• String constants

Data Types
C++ supports different types of data, each of which may be represented differently within a computer's
memory. Data type is used to determine what type of value a variable or a constant can contain throughout
the program.

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 6 of 24


In C++ language, it is compulsory to declare variables with their data type before using them in any
statement. Mainly data types are categorized into following categories:-

1. Fundamental or Basic Data Types :- int, float, char, double, void


2. Derived Data Types :- array, pointer
3. User Defined Data Types :- class, structure, union, enum

1. Fundamental Data Types

(a) Int (Integer):- Integer data type is used to store numeric values without any decimal point.
int keyword is used to refer integer data type. They generally require 2 bytes of memory for their
storage. The range of values that variables of this type can hold lies between -32,768 to +32,767.

Syntax:
int variable_name;
Example:
int roll, marks, age;
roll = 15;
(b) Float:- Float data type is used to store numeric values with decimal point. float keyword is
used to refer integer data type. The storage size of float data type is 4 byte. The range of float
data type is from 3.4x10-38 to 3.4x1038. We can use upto 6 digits after decimal using float data
type.

Syntax:
float variable name;
Example:
float per, area;
per = 20.75;

(c) Char (Character):- Character data type is used to store single character, within single
quotes e.g. 'a', 'z','e' etc. Storage size of char data type is 1. char keyword is used to refer
character data type.

Syntax:
char variable name;
Example:
char ch;
ch = ‘a’;

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 7 of 24


(d) Double:- Double data type is also same as float data type which allows upto 15 digits after
decimal and the range is from 1.7 x 10-308 to 1.7 x 10308 . The storage size of double data type is 8
bytes.

Syntax:
double variable_name;
Example:
double sal;
sal = 450.9876;

(e) Void:- Void data type is used to represent an empty value. It is used as a return type if a
function does not return any value.

Syntax:
void function_name( );
Example:
void sum( );

2. Derived Data Types

Data types that are derived from fundamental data types are called derived data types. Derived
data types don't create a new data type; instead, they add some functionality to the basic data
types. Two derived data type are - Array & Pointer.

(a) Array:- An array is a collection of variables of same type i.e. collection of


homogeneous data referred by a common name. In memory, array elements are stored in a
continuous location.

Syntax:
int array_name[size];

Example:
int age[20];
According to the rules of C++ language, 1st element of array is stored at location age[0] , 2nd
at age[1] & so on.

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 8 of 24


(b) Pointer:- A pointer is a special variable that holds a memory address (location in
memory) of another variable. The asterisk (*) sign is used to declare a pointer variable.

Syntax:
datatype * variable_name;
Example:
int a, *p;
p = &a;
Here, variable 'p' stores the address of variable 'a'.

3. User Defined Data Types

User defined data type is used to create new data types. Different user defined data types are:
class, struct, union, enum.

(a) Struct (Structure):- A structure is a collection of different data types which are grouped
together. In memory, the entire structure variable is stored in sequence. struct keyword is
used to refer structure data type.
Syntax:
struct < structure name>
{
var1;
var2;
-----
-----
};
Example:
struct student
{
char name [20];
int roll;
float marks;
};

(b) Union:- Union is also like structure, i.e. collection of different data types which are
grouped together. In memory, union variables are stored in a common memory location.
Syntax:
union < tag name>
{
var1;

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 9 of 24


var2;
-----
-----
};
Example:
union student
{
char name [20];
int roll;
float marks;
};

(c) Enum (Enumeration):- An enumeration data type is another user-defined type which
provided a way for attaching names to numbers. Enumeration are defined much like
structures, the keyword enum is used to refer enumeration type.
Syntax:
enum < tag name>
{
enumeration list
};
Example:
enum colour
{
red, blue, green, yellow
};

By default, the enumeration is assigned integer values starting with 0 for the first enumerator,
1 for the second, and so on. The value can over-ride the default by explicitly assigning integer
values to the enumerators.

enum colour
{
red = 5, green = 8, blue = 9
};

(d) Class:- A class represents a group of similar objects. A class is a way to bind the data
describing an entity and its associated functions together. To represent classes in C++, it
offers a user-defined data type called class.
Syntax:
class < class name>
{
private :

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 10 of 24


[variable declarations;]
[function declarations;]
protected :
[variable declarations;]
[function declarations;]
public :
[variable declarations;]
[function declarations;]
};

Example:
class department
{
char name[20];
int num_emp;
char h_o_d[20];
public :
add( );
delete( );
print( );
};
department sales, accounts, import;

Operators:
An operator is a special symbol that tells the complier to perform specific mathematical or logical operation
on one or more operands where an operand can be a variable, constant or an expression.
In C++, an operator can either be unary, binary or ternary. If an operator operates on single operand then it is
termed as unary operator. If an operator operates on two operands, it is called binary operator. The operator
that works with three operands is called ternary operator.
The various operators available in C++ are

(a) Arithmetic Operators: The arithmetic operators are used for mathematical
calculations. The arithmetic operators are binary operators that work with any basic type.

There are five arithmetic operators

Addition +
Subtraction -
Multiplication *
Division /
Modulus % this operator produces the remainder.

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 11 of 24


For Example: Now suppose a and b are two operands of type integer then

Operation If a = 7 and b =3

a+b 10

a-b 4

a*b 21

a/b 2

a%b 1

(b) Relational Operators: The relational operators are used to check the relation between
two operands. It is used to make comparison between two operands. Relational operators are
binary operators and hence require two operands. The result of relational operation is a value that
can only be true or false according to the result of the comparison.

There are six relational operators

Less than <


Less than or equal to <=
Greater than >
Greater than or equal to >=
Equal to ==
Not equal to !=

For Example: Now suppose a and b are two operands of type integer then

Operation Result (If a = 7 and b =3)

a<b False

a <= b False

a>b True

a >= b True

a == b False

a!=b True

(c) Logical Operators: Logical operators are used to combine one or more relational
expressions. In C++, there are three logical operators, logical AND (&&), logical OR (||) and
logical NOT (!). The logical AND and logical OR operators are binary operators whereas logical
NOT is an unary operator.

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 12 of 24


Logical AND (&&): The logical AND (&&) is a binary operator that evaluates to true if and
only if both of its operands (expressions) evaluate to true.

Result
Expression1 Expression2 (expression1 &&
expression2)

True True True

True False False

False True False

False False False

Logical OR (||): The logical OR (||) is a binary operator that evaluates to true if and only if
either of its operands (expressions) evaluate to true.

Result
Expression1 Expression2 (expression1 || expression2)

True True True

True False True

False True True

False False False

Logical NOT (!): The logical NOT (!) is an unary operator. The logical NOT operator reverses
the value of the expression i.e., if the expression is true, then !expression is false, and vice versa.

Result
Expression1 (!expression1)

True False

False True

(d) Assignment Operator: The assignment operator (=) is the most commonly used binary
operator in C++. It evaluates the operand on right hand side and then assigns the resulting value
to a variable on the left hand side. The right operand can be a variable, constant, function call or
expression.

variable = expression/constant/function call


Example: a = 3;
x = y + 10;

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 13 of 24


(e) Conditional Operators: C++ offers a conditional operator (? :) that stores a value
depending upon a condition. This operator is ternary operator i.e, it requires three operands. The
general form of conditional operator (?:) is as follows:

expression1 ? expression2 : expression3

If expression1 evaluates to true then the value of the whole expression is the value of
expression2, otherwise, the value of the whole expression is the value of expression3.
For example:
result = (marks>=50) ? ‘P’ : ‘F’ ;

In this example, if (marks>=50) is true than result is assigned value ‘P’ and if it is false than
it is assigned value ‘F’.

(f) Bitwise Operators: C++ provides extensive bit manipulation operators for programmers
who want to communicate directly with the hardware. These operators are used for testing bits or
shifting them either right to left or left to right. Following are the bitwise operators

Operator Meaning

& Bitwise AND

| Bitwise OR

Bitwise Exclusive
^ OR

Bitwise One’s
~ Complement

<< Shift Left

>> Shift Right

(g) Increment (++) and Decrement (--) Operator:


In certain situations, there is a need to increase or decrease the value of an operand by 1. C
provides an increment operator (++) and a decrement operator (--) to increase and decrease the
value of the operand by 1 respectively.
If x is a variable then x++ is equivalent to x = x + 1. This means that value of a variable x is
increased by 1. Similarly, x-- is equivalent to x = x – 1. This means that value of a variable x is
decreased by 1.

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 14 of 24


(h) Sizeof operator:
A sizeof operator is a unary operator that returns the number of bytes required to store a variable
or a data type. This operator always precedes its operand. Here operand may be a variable name
or basic or user defined data type etc.

Syntax:
sizeof(datatype or variable)

Example:
#include<iostream.h>
#include<conio.h>
void main( )
{
int a;
float b;
char c;
cout<< “Integer :” << sizeof(a) << endl;
cout<< “Float :” << sizeof(b) << endl;
cout<< “Character :” << sizeof(char) << endl;
getch( );
}

The output of this program is

Integer : 2
Float : 4
Character : 1

(i) Scope Resolution Operator (: :) : The operator (: :) is known as scope resolution operator.
It has been introduced to access an item that is outside the current scope i.e. it is used to access
the global variables. This operator is also used in distinguishing class members and defining class
methods.

# include <iostream.h>
# include <conio.h>

int amount = 123;

void main( )
{
int amount = 456;
cout << “Global Variable:” << ::amount; << endl;
cout <<”Local Variable:” << amount;
getch( );
}

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 15 of 24


Precedence & Associativity of Operators:
Precedence determines the order which operations are performed during the evaluation of an expression.
Operators with higher precedence are evaluated before operators of lower precedence regardless of the order
in which they appear.
Associativity governs the order in which multiple operators with same precedence are evaluated either from
left to right or right to left.

Operator
Operator Associativity
Category

++, --,+ (unary), & (address-


Unary Operators R→L
of), sizeof

Arithmetic * (multiplication), /, %,+, -


L→R
Operators (subtraction)

Bitwise Shift
& (bitwise AND), | (bitwise OR) L→R
Operators

Relational
<, <=, >=, > L→R
Operators

Equality Operators ==, != L→R

Logical Operators &&, || L→R

Conditional
?: R→L
Operators

Assignment
=, +=, -= etc. R→L
Operators

Selection or Decision Control Statements:


The selection statement means the execution of statement(s) depending upon a condition-test. If a condition
evaluates to true, a course-of-action (a set of statements) is followed otherwise another course-of-action (a
different set of statements) is followed. This selection statement is also called decision control statement
because it helps in making decision about which set-of-statements is to be executed.

The following decision control statements are supported by C++

(a) if statement (b) if-else statement (c) switch statement

The IF statement: The basic decision making statement used in most C++ programs is the if statement.
The different types of if statements are

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 16 of 24


(a) Simple if statement (b) If-else statement (c) Nested if statement (d) Else-if Ladder

(a) Simple If statement:

The if statement is the most simple and powerful decision control statement which is used to
control the sequence of execution of statements. It is used to execute a statement or a statement
block only if the condition is true. No statement(s) is executed when the condition evaluates to false.

The general form is:

if(condition)
{
statement(s);
}
Example: To check if a number is greater than 25.

#include<iostream.h>
#include<conio.h>
void main( )
{
int a;
cout << ”Enter a number : ”;
cin >> a;
if(a > 25)
{
cout << “Number is greater than 25”;
}
getch( );
}

(b) The If-else statement:

The if-else statement allows the programmer to execute a statement block following the if
keyword when the condition is true and execute a different statement block following the else
keyword when the condition is false. In other words, it is a two way branching statement.

The general form is:

if(condition)
{
statement(s);
}
else
{
statement(s);
}

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 17 of 24


Example: To check whether a given number is odd or even.
#include<iostream.h>
#include<conio.h>
void main( )
{
int n;
clrscr( );
cout << ”Enter a number : ”;
cin >> n;
if(n%2 = = 0)
{
cout << “Number is Even”;
}
else
{
cout << “Number is Odd”;
}
}

(c) Nested If statement:

A nested if is an if that has another if in its if’s body or in its else’s body. The different ways
for representing nested if statements are

if(condition1) | if(condition1) | if(condition1)


{ | { | {
if(condition2) | if(condition2) | statement1;
{ | { | }
statement1; | statement1; | else
} | } | {
else | else | if(condition2)
{ | { | {
statement2; | statement2; | statement2;
} | } | }
} | } | else
else | else | {
{ | { | statement3;
statement3; | if(condition3) | }
} | { | }
| statement3; |
| } |
| else |
| { |
| statement4; |
| } |
| } |

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 18 of 24


In an if statement, either there can be if statement(s) in its body-of-if or in its body-of-else or in
both.

Example: To calculate the greatest of three numbers.

#include<iostream.h>
#include<conio.h>
void main( )
{
int a, b, c;
cout << “Enter the three numbers : ”;
cin >> a >> b >> c;
if(a > b)
{
if(a>c)
{
cout << “A =” << a << “is greatest”;
}
else
{
cout << “C =” << c <<“is greatest”;
}
}
else
{
if(b>c)
{
cout << “B =” << b << “is greatest”;
}
else
{
cout << “C =” << c <<“is greatest”;
}
}
getch( );
}

(d) The ELSE-If Ladder:

The else-if ladder is the most general way of writing a program involving multiple
conditions.

The general form is

if(condition1)
{
statement1;

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 19 of 24


}
else if(condition2)
{
statement2;
}
else if(condition3)
{
statement3;
}
.
.
else
{
statement;
}

The conditions are evaluated from the top to downward. As soon as the condition evaluates to
true, the statement associated with it is executed and the rest of the ladder is bypassed. If
none of the conditions are true, the final else gets executed.

Example: To calculate the greatest of three numbers.

#include<iostream.h>
#include<conio.h>
void main( )
{
int a, b, c;
cout << “Enter the three numbers : ”;
cin >> a >> b >> c;
if(a > b && a>c)
{
cout << “A =” << a << “is greatest”;
}
else if(b>a && b>c)
{
cout << “B =” << b << “is greatest”;
}
else
{
cout << “C =” << c <<“is greatest”;
}
getch( );
}

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 20 of 24


The Switch statement: The switch statement is a multi-way decision making statement which selects
one of the several alternatives based on the value of an expression. The switch statement is mainly used to
replace multiple if-else statements.

The general form of the switch statement is

switch(expression)
{
case constant1 : statement(s);
break;
case constant2 : statement(s);
break;
.
.
.
.
[default : statement(s);]
}

Example: To check whether the entered character is vowel or not.

#include<iostream.h>
#include<conio.h>
void main( )
{
char c;
clrscr( );
cout << “Enter the character in capital letters: ”;
cin >> c;
switch(c)
{
Case ‘A’ : cout << “Character is Vowel”;
break;
Case ‘E’ : cout << “Character is Vowel”;
break;
Case ‘I’ : cout << “Character is Vowel”;
break;
Case ‘O’ : cout << “Character is Vowel”;
break;
Case ‘U’ : cout << “Character is Vowel”;
break;
default : cout << “Character is not vowel”;
}
getch( );
}

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 21 of 24


Difference between If-else and Switch statement:

Switch If-else

It can evaluate a relational or logical expression i.e,


It can only test for equality. multiple conditions.

It can handle only integer and character test. It can handle integer, character and floating-point tests.

It is preferred when large numbers of It is preferred when numbers of conditions are less.
conditions are involved.
In switch case label value must be a constant. In if two or more variables are to be compared.

It cannot handle ranges. Each switch case It can handle ranges.


label must be a single value.
The syntax of switch is
The syntax of if-else is
switch(expression)
{ if(condition)
case constant1 : statement(s); {
break; statement(s);
case constant2 : statement(s); }
break; else
. {
. statement(s);
[default : statement(s);] }
}

Scope of Variables: All the variables have their area of functioning, and out of that boundary they
don't hold their value, this boundary is called scope of the variable. There are mainly two types of variable
scopes:

• Global Variables
• Local variables

• Global Variables: Global variables are those, which are once declared and can be used
throughout the lifetime of the program by any class or any function. They must be declared outside
the main() function.

For Example:
#include <iostream.h>
#include<conio.h>
int x; // Global variable declared
int main()
{
int a, b;
a = 10, b = 20;

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 22 of 24


x = a + b;
cout <<"The Sum is = "<< x;
getch( );
}

• Local Variables: Local variables are the variables which exist only between the curly braces, in
which it’s declared. Outside that they are unavailable and lead to compile time error.
For Example:
#include <iostream.h>
#include<conio.h>
int main()
{
int a, b, c; // Local Variables declared
a = 10, b = 20;
c = a + b;
cout <<"The Sum is = "<< c;
getch( );
}

Type Conversion:
The process of converting one predefined type into another is called Type conversion.
Type conversion is usually classified into two categories
(1) Implicit or Automatic Type Conversion
(2) Explicit Type Conversion or Type Casting

Implicit or Automatic Type Conversion: The conversion of data type which is carried out
automatically by the compiler without programmer intervention is called implicit type conversion. When
two data items (variables) of different data types are encountered in the same expression, then the lower
type variable is converted to the higher type variable before the operation proceeds.
The hierarchy of data types is as follows
long double →double →float →long int →int →char
For Example:
int a = 10;
float b = 2.5;
double d;
d = a * b;

In the above expression, firstly the int value is converted to float. Then, this float value is multiplied
with another float value and result is a float value. Now as left hand side has data type double so
finally this float type is converted to double.

Explicit Type Conversion or Type Casting: An explicit type conversion is user defined that
forces an expression to be of specific type. The explicit conversion of an operand to a specific type is called
Type Casting.

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 23 of 24


Syntax:
(type) expression
Here type is a valid C++ data type to which the conversion is to be done.
For Example:
int m = 5;
int n = 9;
float c;
c = (float) m/n;

In the above formula if casting is not performed than the result of the expression gives
us 0 value but when the casting is done the above expression will converted into float
type that will result 0.555556 value.

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 24 of 24

You might also like