Skip to main content

Command Palette

Search for a command to run...

Simple programs using Operators, and type conversion.

Published
2 min read

Aim

The aim is to illustrate the mechanism of explicit type conversion using the Type Cast Operator in C++. This exercise demonstrates how values are handled when converting between basic integer (int) and floating-point (float) data types, specifically employing the C++ function-call notation for casting.

Algorithm

  1. Initialize an integer variable (intvar) with the value 25.

  2. Initialize a floating-point variable (floatvar) with the value 35.87.

  3. Display the initial values of intvar and floatvar.

  4. Apply explicit type casting using float(intvar) to convert the integer value to a float, and display the result.

  5. Apply explicit type casting using int(floatvar) to convert the float value to an integer, and display the result.

  6. Terminate the program.

Program

#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
    int intvar=25;
    float floatvar=35.87;
    cout<<"intvar = "<<intvar;
    cout<<"\nfloatvar = "<<floatvar;
    cout<<"\nfloat(intvar) = "<<float(intvar);
    cout<<"\nint(floatvar) = "<<int(floatvar);
    getch();
}

Output

intvar = 25
floatvar = 35.87
float(intvar) = 25
int(floatvar) = 35

Result/Discussion

The program successfully demonstrates the use of the explicit type cast operator in C++ notation, specifically type-name (expression). When the integer variable intvar (value 25) was converted to a float, the result retained the value 25. However, when the float value 35.87 was explicitly converted to an integer using int(floatvar), the fractional part of the value was truncated, yielding the result 35. C++ permits this explicit conversion, allowing the programmer control over type handling, even when it results in a loss of precision.

181 views

More from this blog

Shanlaksh

16 posts