Programming in C: Unit I (b): Introduction to C

Type Conversion and Typecasting

Syntax with Example C Programs

Till now we have assumed that all the expressions involved data of the same type. But what happens when expressions involve two different data types, like multiplying a floating point number and an integer.

TYPE CONVERSION AND TYPECASTING

Till now we have assumed that all the expressions involved data of the same type. But what happens when expressions involve two different data types, like multiplying a floating point number and an integer. Such type of situations are handled either through type conversion or typecasting.

Type conversion or typecasting of variables refers to changing a variable of one data type into another. Type conversion is done implicitly, whereas typecasting has to be done explicitly by the programmer. We will discuss both of them here.

Type Conversion

Type conversion is done when the expression has variables of different data types. To evaluate the expression, the data type is promoted from lower to higher level where the hierarchy of data types (from higher to lower) can be given as: double, float, long, int, short, and char. Figure 2.14 shows the conversion hierarchy of data types.

Type conversion is automatically done when we assign an integer value to a floating point variable. Consider the code given below in which an integer data type is promoted to float. This is known as promotion (when a lower level data type is promoted to a higher type).

float x;

int y;

x = y;

Now, x = 3.0, as automatically integer value is converted into its equivalent floating point representation. In some cases, when an integer is converted into a floating point number, the resulting floating point number may not exactly match the integer value. This is because the floating point number format used internally by the computer cannot accurately represent every possible integer number. So even if the value of x = 2.99999995, you must not worry. The loss of accuracy because of this feature would be always insignificant for the final result. Let us summarize how promotion is done:

• float operands are converted to double.

• char or short operands whether signed or unsigned are converted to int.

• If any one operand is double, the other operand is also converted to double. Hence, the result is also of type double.

• If any one operand is long, the other operand is also converted to long. Hence, the result is also of type long.

Consider the following group of statements:

float f = 3.5;

int i;

i = f;

The statement i = f results in f to be demoted to type int, i.e., the fractional part of f will be lost and i will contain 3 (not 3.5). In this case demotion takes place, i.e., a higher level data type is converted into a lower type. Whenever demotion occurs, some information is lost. For example, in this case the fractional part of the floating point number is lost.

Similarly, if we convert an int to a short int or a long int to int, or int to char, the compiler just drops the extra bits (Figure 2.16).

Note

No compile time warning message is generated when information is lost while demoting the type of data.

Thus we can observe the following changes are unavoidable when performing type conversions.

• When a float value is converted to an int value, the fractional part is truncated.

• When a double value is converted to a float value, rounding of digits is done.

• When a long int is converted into int, the excess higher order bits are dropped.

These changes may cause incorrect results.

Typecasting

Typecasting is also known as forced conversion. Type- casting an arithmetic expression tells the compiler to represent the value of the expression in a certain way. It is done when the value of a higher data type has to be converted into the value of a lower data type. But this casting is under the programmer's control and not under compiler's control. For example, if we need to explicitly typecast an integer variable into a floating point variable, then the code to perform typecasting can be given as:

float salary = 10000.00;

int sal;

sal = (int) salary;

When floating point numbers are converted to integers (as in type conversion), the digits after the decimal are truncated. Therefore, data is lost when floating-point representations are converted to integral representations. So in order to avoid such type of inaccuracies, int type variables must be typecast to float type.

As we see in the code, typecasting can be done by placing the destination data type in parentheses followed by the variable name that has to be converted. Hence, conclude that typecasting is done to make a variable of one data type to act like a variable of another type.

We can also typecast integer values to its character equivalent (as per ASCII code) and vice versa. Typecasting is also done in arithmetic operations to get correct result. For example, when dividing two integers, the result can be of floating type. Also when multiplying two integers the result can be of long int. So to get correct precision value, typecasting can be done. For instance:

int a = 500, b = 70 ;

float res;

res = (float) a/b;

Let us look at some more examples of typecasting.

• res = (int) 9.5;

9.5 is converted to 9 by truncation and then assigned to res.

• res = (int) 12.3 / (int) 4.2;

It is evaluated as 12/4 and the value 3 is assigned to res.

• res = (double) total/n;

total is converted to double and then division is done in floating point mode.

• res = (int)(a+b);

The value of a+b is converted to integer and then assigned to res.

• res = (int) a + b;

a is converted to int and then added with b.

• res = cos ((double) x);

It converts x to double before finding its cosine value.

24. Write a program to convert a floating point number into the corresponding integer.

#include <stdio.h>

#include <conio.h>

int main()

{

float f num;

int i_num;

clrscr();

printf("\n Enter any floating point number: ");

scanf("%f", &f_num);

i_num = (int) f_num;

printf("\n The integer variant of %f is = %d", f_num, i_num);

return 0;

}

Output

 Enter any floating point number: 23.45

The integer variant of 23.45 is = 23

25. Write a program to convert an integer into the corresponding floating point number.

#include <stdio.h>

#include <conio.h>

int main()

{

float f num;

int i_num;

clrscr();

printf("\n Enter any integer: ");

scanf("%d", &i_num);

f_num = (float) i_num;

printf("\n The floating point variant of %d is = %f", i_num, f_num);

return 0;

}

Output

Enter any integer: 12

The floating point variant of 12 is = 12.00000

26. Write a program to calculate a student's result based on two examinations, one sports event, and three activities conducted. The weightage of activities = 30%, sports = 20%, and examination = 50%.

#include <stdio.h>

#include <conio.h>

#define ACTIVITIES_WEIGHTAGE 30

#define SPORTS_WEIGHTAGE 20

#define EXAMS_WEIGHTAGE 50

#define EXAMS_TOTAL 200

#define ACTIVITIES_TOTAL 60

#define SPORTS_TOTAL 50

int main()

{

int exam_score1, activities_score1,sports_score;

int exam_score2, activities_score2, activities_score3;

float exam_total, activities_total;

float total_percent, exam_percent, sports_percent, activities_percent;

clrscr();

printf("\n Enter the score obtained in two examinations (out of 100): ");

scanf("%d %d", &exam_score1, &exam_score2);

printf("\n Enter the score obtained in sports events (out of 50): ");

scanf("%d", &sports_score);

printf("\n Enter the score obtained in three activities (out of 20): ");

scanf("%d %d %d", &activities_score1, &activities_score2, &activities_score3);

exam total = exam_score1 + exam_score2;

activities total = activities_score1 + activities_score2+ activities_score3;

exam_percent = (float) exam_total * EXAMS WEIGHTAGE / EXAMS TOTAL;

sports_percent = (float) sports_score * SPORTS WEIGHTAGE / SPORTS_TOTAL;

activities_percent = (float) activities_total * ACTIVITIES_WEIGHTAGE/ ACTIVITIES_TOTAL;

total_percent = exam_percent + sports_ percent + activities_percent;

printf("\n\n ******************** RESULT ********************");

printf("\n Total percent in examintaion : %f", exam_percent);

printf("\n Total percent in activities : %f", activities_percent);

printf("\n Total percent in sports : %f", sports_percent);

printf("\n ----------------------------------------------------");

printf("\n Total percentage: %f", total_ percent);

return 0;

}

Output

Enter the score obtained in two examinations (out of 100): 78 89

Enter the score obtained in sports events (out of 50): 34

Enter the score obtained in three activities (out of 20): 19 18 17

****** RESULT *******

Total percent in examintaion: 41.75

Total percent in activities : 27

Total percent in sports : 13

Total percentage : 82

Programming in C: Unit I (b): Introduction to C : Tag: : Syntax with Example C Programs - Type Conversion and Typecasting