Chapter2 PDF
Chapter2 PDF
Chapter2 PDF
void main()
{ int a=10;
float b=40.5, result;
result=a+b;
cout<<"The sum is "<<result; }
Output:
The sum is 50.5.
In this case, variable a is of type int while b is of type float. While solving the
expression a+b, the temporary variable of type float is created to store value of a and then
two float values are added. The result is of type float and stored in variable result. Here,
data type int is promoted to float. Thus, it is also known as standard data type
promotion.
The other implicit conversions are
Int and float -> float
Int and long -> long
Int and double -> double
Long and float -> float
Float and double -> double
But, sometime programmer needs to convert a value from one type to another explicitly
in a situation where the compiler will not do it automatically. This type of conversion is
called explicit conversion or type casting. An example:
void main()
{ int a=4000;
long result;
result=a*100;
cout<<"The product is "<<result; }
Output:
The product is 6784 // Error!!!!!
Here, while solving the expression long(a)*100 in above program, integer type
variable a is converted into long type. For this, a temporary variable of type long is
created to store value of a and this long value is multiplied by 100 and result is also of
type long. The long result is stored in variable result.
Without casting, the result is not correct. This is because multiplication of two
integers (i.e. a and 100) results integer value (i.e. 4000000). But this integer value is
beyond the range of integer. Thus, garbage value is stored in result variable.
Pointer:
A pointer is a variable that stores a memory address of a variable. Pointer can
have any name that is legal for other variable and it is declared in the same fashion like
other variables but is always preceded by ‘ *’ ( asterisk) operator. Pointers are declared
and initialized as in C. The additional feature of C++ is that has concept of constant
pointer and pointer to constant. The constant pointer is defined as
Data_type * const ptr_name;
An example:
void main()
{ int j=10;
int *const ptr=&j; //constant pointer
*ptr=20;//OK
ptr++; //Error
}
Pointer to Constant:
It is defined as
Data_type const *ptr_name;
An example:
void main()
{
Prepared By: 2
Er. Dipesh Bista
Acme Engineering College
int const j=10;
int const * ptr=&j;// pointer to constant
*ptr=20;//Error
ptr++; //OK
}
Characteristics:
¾ Memory can be initialized using new operator. This is done as
Pointer _variable= new data_type(initial_value);
e.g. int *p;
p=new int(35);
will allocates two bytes of memory and 35 is allocated at this memory initially.
¾ new can be used to allocate a memory space for data types including user defined
types such as arrays, structures and classes. Its syntax is
pointer_variable=new data_type[size]; // for array
e.g.
int *p;
p=new int[100];
will allocates 200 bytes memory and starting address is stored at pointer
variable p.
delete:
If a program reserves many chunks of memory using new, eventually all the available
memory will be reserved and the system will crash. To ensure safe and efficient use of
memory, the new operator is matched by a corresponding delete operator. This operator
returns the memory to the operating system when a data object in no longer needed.
Thus, delete operator is used to release the memory space for reuse by destroying the
object when it is no longer needed. The syntax
delete pointer-variable; // general syntax
delete [] pointer-variable; // in case of array
An example, a program which asks for a number of students at run time and
according to the number of students in a class, the program reserves the memory to store
percentage of each student and finally calculates average percentage of class.
#include<iostream.h>
void main()
{
int num,*ptr;
float sum=0;
cout<<"How many number of students?"<<endl;
cin>>num;
ptr=new int[num];
cout<<"Enter each students marks"<<endl;
for(int i=0;i<num;i++)
{
cin>>*(ptr+i);
sum+=*(ptr+i);
}
float avg= sum/num;
cout<<"The average is "<<avg;
delete []ptr;
}
const:
This is C++ qualifier used for creating symbolic constant. Its syntax is
const data_type variable_name= value;
e.g. const int size=10;
It specifies that the value of a variable (here, size) will not change throughout the
program. Any attempt to alter the value of a variable defined with this qualifier will give
error message by compiler. It is used for variables which do not change throughout the
Prepared By: 4
Er. Dipesh Bista
Acme Engineering College
program like PI while calculating area of circle. In C++, the variable defined with this
qualifier const should be initialized.
Enumeration:
The dictionary meaning of enumeration is counting, go through a list of articles naming
them one by one. The process enumeration provides user defined data type, called
enumerated data type which provides a way for attaching names to numbers. The syntax
is
enum tag_name {name1, name2, name3, ….};
e.g. enum flag{false, true};
enum colour{red, blue, green, white};
Here, colour is enumerated data type whose permissible values are red, blue, green and
white. Here, possible values red, blue, green and white are also called enumerators. These
enumerators are attached with numbers 0,1,2 and 3 (i.e. o for red, 1 for blue and so on).
Variables can be defined using this enumerated data type. These variables store only
those values defined while defining enumerated data type.
e.g.
colour foreground;
foreground=red // ok
foreground=yellow; // not ok as yellow is not possible value for data type colour
By default, the enumerators are assigned integers values starting with o for the first
enumerator, 1 for second and so on. These can be explicitly assigned by the programmer
as following.
enum colour{red=7,blue, green, white}; // here, blue=8, green=9 and white=10
Characteristics:
¾ Although the enumerated data types are treated internally as integers, C++ does
not permit an int value to be automatically converted to an enum value. E.g.
colour foreground=2; // error
colour foreground= (colour)2 // ok
¾ An enumerated value i.e. enumerator can be used in place of an int value. E.g.
int num= red; // ok
¾ The enumeration provides an alternative means for creating symbolic constants.
The enumerator’s value can be changed in the program.
¾ The anonymous enums (without enum_tag_name) can be created in C++.
e.g. enum {red,blue,green,white};
An example:
#include<iostream.h>
void main()
{
enum days{sun,mon,tue,wed,thu,fri,sat};
days day1,day2;
int mid_day;
day1=sun;
Prepared By: 5
Er. Dipesh Bista
Acme Engineering College
day2=sat;
mid_day=wed;
cout<<"day1= <<day1<<endl<<"day2="<<day2<<endl<<"Middle="<<mid_day;
}
Output:
day1=0
day2=6
Middle=3
An another example which asks a number and test it for even or odd.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num;
enum flag{false, true};
flag even;
cout<<"Enter a number to check even or odd"<<endl;
cin>>num;
if(num%2==0)
even=true;
else
even =false;
if(even)
cout<<"The number is even";
else
cout <<"The number is odd";
getch();
}
Comments:
Comments in programming languages are those statements which are not needed to
compile by the compiler. C++ supports both single line and multiple line comments.
Single line comment is also known as double slash comment (i.e. //). It this comment is to
be used for multiple line, we should use // for each line separately.
e.g.
//This is single line
// comment used for multiple line
Again, it supports C style comment (i.e. /* */). This type of comment is generally used
for multiple lines. The lines between /* and */ are not compiled.
Prepared By: 6
Er. Dipesh Bista
Acme Engineering College