PF - Lecture 8
PF - Lecture 8
DEPARTMENT OF CS&IT
Type Conversion
(lecture # 8)
1. Namespaces
• Namespaces
• Using Directive
2. Type Conversion
• Type Conversion
• Implicit Type Conversion
• Explicit Type Conversion
• Explicit Type Conversion: Style
• Explicit Type Conversion: Example
3. Exercise
Programming Fundamental 3
Namespaces
Programming Fundamental 4
using Directive
• The keyword using is used to introduce a name from a namepace into the current
declarative region.
• For instance, the directive
using namespace std;
says that all the program statements that follow are within the std namespace.
• Files in standard C++ library declare all of their entities within the std namespace,
for instance, cout, cin.
• We generally include it in all programs that use any entity defined in iostream.
Programming Fundamental 5
Type Conversion
• Often the data needs to converted from one type to another type. This is called
type conversion.
• Two ways to convert a data type
• Implicit Type Conversion
• Explicit Type Conversion
Programming Fundamental 6
Implicit Type Conversion
• Done automatically by the compiler whenever data from different types is mixed.
• When a value from one type is assigned to another type, the compiler implicitly
converts the value into a value of the new type. For example:
int main()
{
int count = 5;
float weight = 155.5;
double totalweight = count * weight;
cout << ‘‘Total weight is ’’ << totalweight << endl ;
return 0;
}
Programming Fundamental 7
Explicit Type Conversion
Programming Fundamental 8
Explicit Type Conversion
int main()
{
float num = 98.74;
int x1 = (int) num; // C-style cast
int x2 = int (num); // C++ function-style cast
int x3 = static cast(num); // C++ cast operator
cout << ‘‘x1 = ’’ << x1 << endl ;
cout << ‘‘x2 = ’’ << x2 << endl ;
cout << ‘‘x3 = ’’ << x3 << endl ;
return 0;
}
• The following is the output of the above example:
x1 = 98
x2 = 98
x3 = 98
Programming Fundamental 9
Explicit Type Conversion: Example
int main()
{
int intVar = 1500000000;
intVar = (intVar * 10)/10;
cout << ‘‘intVar = ’’ << intVar << endl ;
int intVar = 1500000000;
intVar = (static cast(intVar) * 10)/10;
cout << ‘‘intVar = ’’ << intVar << endl ;
return 0;
}
• Here is the program output:
intVar = 211509811 // wrong answer
intVar = 1500000000 // correct answer
Programming Fundamental 10
Excercise
Q). Write and run a program that simulates a simple calculator. It reads two integers
and a character. If the character is a ‘+’, the sum is printed; if it is a ‘-’, the
difference is printed; if it is a ‘*’, the product is printed; if it is a ‘/’, the quotient is
printed; and if it is a ‘%’, the remainder is printed.
Programming Fundamental 11
REFERENCES
1. Deitel, Paul J., and Harvey M. Deitel. "C++: how to program/Paul Deitel,
Harvey Deitel." (2012). (Chapter 4)
2. Zak, Diane. Introduction to Programming with C++. Cengage Learning, 2013.
12
Programming Fundamental
THANKS