Welcome !!

NICETECHVIDYA

Tutorials

Web Designs

You are welcome to Aptech Designers, designed by Pratik from Nepal.

Creativity is my passion. Logo describes your details about company.

Graphics Design needs vision to create yours unique digital concept.

Responsive and All Browser Compatible Dynamic Web Layouts our target.

Home Python C Language J A V A Our Courses
This WebSite is under Construction....

Thursday 10 March 2022

16.Type conversion and typecasting

 

Type conversion:

 

In an assigning statement if RHS variable and LHS expression are of the same type then there would be no problem in assigning.

If both are of different types then care must be taken to properly assign expression to variable without loosing precision.

 

Auto conversion:

In most of the cases the expression type is automatically converted into variable type without loosing any precision called auto casting.

 

Example :


#include<stdio.h>
void main()
{
char ch;
int x;
clrscr();
ch=’a’;        /* automatically converted from char to int */
x=ch;
printf(“%d”,x);
getch();
}

Output:

97

 

Example :


#include<stdio.h>
void main()
{
int x=65;
char ch;
clrscr();
ch=x;          /* automatically converted from int to char */
printf(“%c”,ch);
getch();
}

Output:

A

 

Example :


#include<stdio.h>
void main()
{
float x=12.25;
int y;
clrscr();
y=x;                   /*automatically converted from float to int */
printf(“%d”,y);
getch();
}

Output:

12

 

Typecasting:

Some times there may be loss of precision while assigning one type of expression to another type of variable.

We need to give an instruction to the compiler in order to convert expression type into the variable type using typecast operator.

Converting one type into another explicitly by using typecast operator is called typecasting

syntax: 

<variable> = (variable type)<expression>

 

 

Example:


#include<stdio.h>
void main()
{
int x,y;
float z;
clrscr();
x=5;
y=2;
z=x/y;
printf(“%f”,z);
getch();
}

Output:

2.000000

 

Example explained :

In the above example x/y is of integer, couldn’t be assigned to the float type properly.

Rectifying the example:


#include<stdio.h>
void main()
{
int x,y;
float z;
clrscr();
x=5;
y=2;
z=(float)x/y;
printf(“%f”,z);
getch();
}

Output:

2.500000

 

Example :


#include<stdio.h>
void main()
{
float x,a,b;
clrscr();
x=(int)7.5;                             /* converted float into int */
a=(int)21.3/(int)4.5;               /* converted as 21/4 of int */
b=21.3/4.5;                          
printf(“x=%f\na=%f\nb=%f”,x,a,b);
getch();
}

Output :

x=7.000000

a=5.000000

b=2.733333

0 comments:

Post a Comment