Professional Documents
Culture Documents
Lect 09 Datatype Struct Union
Lect 09 Datatype Struct Union
UNION
Datatypes
Different types of data
Ways to declare data
Basically there are 3 types of data:
Char
Int
Float
void main()
{
printf ("char type = %d bytes\n", sizeof (char));
printf ("short integer = %d bytes\n", sizeof (short));
printf ("integer = %d bytes\n", sizeof (int));
printf ("long integer = %d bytes\n", sizeof (long));
printf ("floating point = %d bytes\n", sizeof (float));
printf ("double precision float = %d bytes\n", sizeof (double));
}
Structure (1/3)
Purpose of structure:
to have one single name variable to handle
different types of variables for better management
of program
Example of structure is information about one
customer
For a customer data may include:
•Full name •Age
•Title •Salary
•Citizenship number
•Gender (M/F)
Structure (2/3)
Struct can be nested, so there can be struct inside a
struct
Format for struct:
struct structure_name
{
data_type member1;
data_type member2;
. .
data_type membern;
};
Structure (3/3)
Example of the above struct:
struct person
{
char name[50];
char title[10];
char citizenship_no[16];
char gender;
int age;
float salary;
};
Structure assignment
Create structure distance
Distance consists of kilometer, meter, milimeter
Create program to calculate distance by adding:
Distance1 + distance2
distance1 & distance2 are entered from stdin
Check for the maximum of meter is 999 meter
Length > 1000 meter must be converted into kilometer
Check for the maximum of milimeter is 999 milimeter
Length > 1000 milimeter must be converted into meter
Union (1/2)
Union is a value that may have any of several
representations or formats; or it is a data structure
that consists of a variable which may hold such a
value
Union can be of the same type of value but with
different datatype
For example a value of floating point can be
duplicated into integer, but of course the value will
not be the same
Union (2/2)
Format for union:
union union_var
{
float value;
char value_char[4];
int value_int;
};
Illustration of a union with name value:
1 byte 1 byte 1 byte 1 byte
value
value_char
value_int
Example of a union
Look at the program below:
Program big-small-endian.c
Assignment for structure
create a variable structure consisting of real and
imaginary number (type of floating point)
Go back to your
Structure of an array of 5 elements
Program should ask for real and imaginary number
Program should find magnitude and phase which is:
sqrt(real*real+im*im)
atan(im/real)
Find the average magnitude and standard deviation
Assignment for structure (ABC formula)