36 Programming and Data Structures
Syntax variable_name=constant
or
data_type variable_name=constant
Examples x=2; where x is an integer variable,
int y=2;
int x=y=z=l;
The third example of initialization is also a valid statement. One or more variables can be initialized
with one value using such a format.
2.12 TYPE CONVERSION
Sometimes a programmer needs the result in certain data type, for example, division of 5 with 2 should
return flo a t value. Practically the compiler always returns integer values because both the arguments
are of integer data type. This can be followed by execution of the following program.
2.4 Write a program to change data type of results obtained by division operation.
# include <stdio.h>
# include <comio.h>
void main ()
{
clrscr ();
printf ("o Division operation
printf(" Two Integers (5 & 2)
printf(" One int & one float (53 & 2)
printf(" Two Integers (5 6 c 2)
>
Result*);
: %d",5/2);
: %g",5.5/2);
: %g",(float)5/2);
OUTPUT;
Division operation Result
Two Integers (5 & 2) : 2
One int & one float (5.5 & 2)
:
2.75
Two Integers (5 & 2) : 2.5
Explanation In the first division operation data types are chosen as integer. Hence, the result turns
out to be an integer. Actually the result should be a f lo a t value but the compiler returns an integer
value. In the second division operation a flo a t value is divided by an integer. The result of division
in this case yields a flo a t. The limitation of the first operation is removed in the third division
operation using type conversion. Here, both the values are of integer type. The result obtained is
converted into f lo a t. The program uses type casting which is nothing but putting data type in a pair
parenthesis before operation. A programmer can specify any data type.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.12.232