Example: C structure
Program to add two distances which is in feet and inches
#include <stdio.h>
struct Distance
{
int feet;
float inch;
} dist1, dist2, sum;
int main()
{
printf("1st distance\n");
printf("Enter feet: ");
scanf("%d", &dist1.feet);
printf("Enter inch: ");
scanf("%f", &dist1.inch);
printf("2nd distance\n");
printf("Enter feet: ");
scanf("%d", &dist2.feet);
printf("Enter inch: ");
scanf("%f", &dist2.inch);
// adding feet
sum.feet = dist1.feet + dist2.feet;
// adding inches
sum.inch = dist1.inch + dist2.inch;
// changing feet if inch is greater than 12
while (sum.inch >= 12)
{
++sum.feet;
sum.inch = sum.inch - 12;
}
printf("Sum of distances = %d\'-%.1f\"", sum.feet, sum.inch);
return 0;
}
Output1st distance Enter feet: 12 Enter inch: 7.9 2nd distance Enter feet: 2 Enter inch: 9.8 Sum of distances = 15'-5.7"
Keyword typedef
Keyword typedef can be used to simplify syntax of a structure.struct Distance{
int feet;
float inch;
};
int main() {
structure Distance d1, d2;
}
is equivalent totypedef struct Distance{
int feet;
float inch;
} distances;
int main() {
distances dist1, dist2, sum;
}
No comments:
Post a Comment
Note: only a member of this blog may post a comment.