Cycle 02
Operators, Expressions & Type Conversions
Implicit and Explicit Type Conversions (Type Casting)
Problem Statement
Write a Turbo C++ program to demonstrate both Implicit Type Conversion (type promotion by compiler) and Explicit Type Conversion (C-style cast and functional cast) during float and integer arithmetic.
#include <iostream.h>
#include <conio.h>
void main() {
int intVal = 17;
int intDiv = 5;
float floatResult;
double doubleVal = 45.789;
int castedInt;
clrscr();
cout << "--- Implicit Type Conversion ---" << endl;
// Without casting: integer division truncates decimal part
floatResult = intVal / intDiv;
cout << "17 / 5 without casting = " << floatResult << " (Truncated integer division)" << endl;
cout << "\n--- Explicit Type Conversion (C-Style Casting) ---" << endl;
// Explicitly casting intVal to float promotes expression to float division
floatResult = (float)intVal / intDiv;
cout << "(float)17 / 5 = " << floatResult << " (Accurate float division)" << endl;
// Explicitly casting float using functional notation float(x)
floatResult = float(intVal) / intDiv;
cout << "float(17) / 5 = " << floatResult << " (Functional casting)" << endl;
cout << "\n--- Truncating Conversion ---" << endl;
castedInt = (int)doubleVal;
cout << "Original Double: " << doubleVal << endl;
cout << "Casted to Int: " << castedInt << " (Fractional part removed)" << endl;
getch();
}
Question 2 of 2